### Make a GET request Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md This example shows how to make a GET request to a URL and print the response status and text. ```python async def main(): async with aiohttp.ClientSession() as session: async with session.get('http://httpbin.org/get') as resp: print(resp.status) print(await resp.text()) asyncio.run(main()) ``` -------------------------------- ### Make a POST request Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of how to make an HTTP POST request. ```python session.post('http://httpbin.org/post', data=b'data') ``` -------------------------------- ### Running the Application Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Calling run_app() to start the web server. ```python web.run_app(app) ``` -------------------------------- ### WebSocket Communication Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of establishing a WebSocket connection and sending/receiving messages. ```python async with session.ws_connect('http://example.org/ws') as ws: async for msg in ws: if msg.type == aiohttp.WSMsgType.TEXT: if msg.data == 'close cmd': await ws.close() break else: await ws.send_str(msg.data + '/answer') elif msg.type == aiohttp.WSMsgType.ERROR: break ``` -------------------------------- ### Route Decorators Example Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Using route decorators to define routes and handlers. ```python routes = web.RouteTableDef() @routes.get('/') async def hello(request): return web.Response(text="Hello, world") app = web.Application() app.add_routes(routes) web.run_app(app) ``` -------------------------------- ### Application Setup and Routing Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Creating an Application instance and registering a request handler on a specific HTTP method and path. ```python app = web.Application() app.add_routes([web.get('/', hello)]) ``` -------------------------------- ### Optimized Route Addition Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example showing an optimized way to add multiple routes for the same path. ```python app.add_routes([web.get('/path1', get_1), web.post('/path1', post_1), web.get('/path2', get_2), web.post('/path2', post_2)] ``` -------------------------------- ### Basic AppRunner and TCPSite Setup Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_reference.md This snippet demonstrates the fundamental steps to initialize an aiohttp application, set up an AppRunner, and start a TCP site to listen on a specific port. It includes starting the site and waiting for a finish signal before cleaning up resources. ```python runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, 'localhost', 8080) await site.start() # wait for finish signal await runner.cleanup() ``` -------------------------------- ### Other HTTP methods Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Examples of other HTTP methods like PUT, DELETE, HEAD, OPTIONS, and PATCH. ```python session.put('http://httpbin.org/put', data=b'data') session.delete('http://httpbin.org/delete') session.head('http://httpbin.org/get') session.options('http://httpbin.org/get') session.patch('http://httpbin.org/patch', data=b'data') ``` -------------------------------- ### User session management with aiohttp_session Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example demonstrating how to set up and use user sessions with the aiohttp_session third-party library. ```python import asyncio import time import base64 from cryptography import fernet from aiohttp import web from aiohttp_session import setup, get_session, session_middleware from aiohttp_session.cookie_storage import EncryptedCookieStorage async def handler(request): session = await get_session(request) last_visit = session.get("last_visit") session["last_visit"] = time.time() text = "Last visited: {}".format(last_visit) return web.Response(text=text) async def make_app(): app = web.Application() # secret_key must be 32 url-safe base64-encoded bytes fernet_key = fernet.Fernet.generate_key() secret_key = base64.urlsafe_b64decode(fernet_key) setup(app, EncryptedCookieStorage(secret_key)) app.add_routes([web.get('/', handler)]) return app web.run_app(make_app()) ``` -------------------------------- ### Route Registration for WebSocket Handler Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example of how to register the WebSocket handler with the application's router for HTTP GET requests. ```python app.add_routes([web.get('/ws', websocket_handler)]) ``` -------------------------------- ### Reading Binary Response Content Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of reading the response body as raw bytes. ```python print(await resp.read()) ``` -------------------------------- ### asyncSetUp example Source: https://github.com/aio-libs/aiohttp/blob/master/docs/testing.md Example of overriding asyncSetUp for asynchronous setup in a TestCase. ```python async def asyncSetUp(self): await super().asyncSetUp() await foo() ``` -------------------------------- ### Manual session closing Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of creating a session without a context manager and manually closing it. ```python session = aiohttp.ClientSession() async with session.get('...'): # ... await session.close() ``` -------------------------------- ### Redirect to Absolute URL Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example of raising HTTPFound to redirect a user to an absolute URL. ```python raise web.HTTPFound('/redirect') ``` -------------------------------- ### Chaining GET and POST requests with streaming content Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Illustrates how the streaming content from one response can be used as the data for another POST request. ```python resp = await session.get('http://python.org') await session.post('http://httpbin.org/post', data=resp.content) ``` -------------------------------- ### POSTing form-encoded data Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of sending form-encoded data by passing a dictionary to the 'data' argument. ```python payload = {'key1': 'value1', 'key2': 'value2'} async with session.post('http://httpbin.org/post', data=payload) as resp: print(await resp.text()) ``` -------------------------------- ### Registering Handlers with add_routes Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Registering handlers for specific HTTP methods and paths using helpers like get() and post(). ```python app.add_routes([web.get('/', handler), web.post('/post', post_handler), web.put('/put', put_handler)]) ``` -------------------------------- ### Redirect to View Name Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example of redirecting to a view named 'login' using the router. ```python async def handler(request): location = request.app.router['login'].url_for() raise web.HTTPFound(location=location) router.add_get('/handler', handler) router.add_get('/login', login_handler, name='login') ``` -------------------------------- ### Streaming upload using an asynchronous generator Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of streaming data generated on the fly using an asynchronous generator. ```python async def data_generator(): for i in range(10): yield f"line {i}\n".encode() async with session.post("https://httpbin.org/post", data=data_generator()) as resp: print(await resp.text()) ``` -------------------------------- ### JSON Request Example Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md How to send a JSON payload in a POST request using the 'json' parameter. ```python async with aiohttp.ClientSession() as session: await session.post(url, json={'test': 'object'}) ``` -------------------------------- ### Passing string content as param Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of passing raw string content as a parameter, noting that '+' is not encoded. ```python async with session.get('http://httpbin.org/get', params='key=value+1') as r: assert str(r.url) == 'http://httpbin.org/get?key=value+1' ``` -------------------------------- ### Login Form Handling with Redirect Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example of a login handler that validates POST data and redirects to the index page upon successful login, or displays an error. ```python @aiohttp_jinja2.template('login.html') async def login(request): if request.method == 'POST': form = await request.post() error = validate_login(form) if error: return {'error': error} else: # login form is valid location = request.app.router['index'].url_for() raise web.HTTPFound(location=location) return {} app.router.add_get('/', index, name='index') app.router.add_get('/login', login, name='login') app.router.add_post('/login', login, name='login') ``` -------------------------------- ### Uploading a file with default multipart encoding Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of uploading a file using multipart encoding by passing a file object to the 'data' argument. ```python url = 'http://httpbin.org/post' files = {'file': open('report.xls', 'rb')} await session.post(url, data=files) ``` -------------------------------- ### Accessing POST form data Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example of how to access form data submitted via a POST request. ```python async def do_login(request): data = await request.post() login = data['login'] password = data['password'] ``` -------------------------------- ### Route decorators with class-based views Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Example of using route decorators with class-based views to define routes for different HTTP methods. ```python routes = web.RouteTableDef() @routes.view("/view") class MyView(web.View): async def get(self): ... async def post(self): ... ``` -------------------------------- ### HTML Form for File Upload Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md An example HTML form that allows users to upload an MP3 file, with the enctype attribute set to 'multipart/form-data'. ```html
``` -------------------------------- ### FileResponse Example Source: https://github.com/aio-libs/aiohttp/blob/master/docs/migration_to_2xx.md Example of using FileResponse to serve a file. ```python3 async def handle(request): return web.FileResponse('path-to-file.txt') ``` -------------------------------- ### ClientSession Usage Example Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_reference.md This example demonstrates how to create a ClientSession and make a GET request. ```APIDOC ## ClientSession Usage Example ### Description This example shows how to initialize a `ClientSession` and use it to fetch content from a URL. ### Code ```python import aiohttp import asyncio async def fetch(client): async with client.get('http://python.org') as resp: assert resp.status == 200 return await resp.text() async def main(): async with aiohttp.ClientSession() as client: html = await fetch(client) print(html) asyncio.run(main()) ``` ``` -------------------------------- ### Import necessary modules Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Begin by importing the aiohttp module, and asyncio. ```python import aiohttp import asyncio ``` -------------------------------- ### Client Example Source: https://github.com/aio-libs/aiohttp/blob/master/README.rst Example of how to get content from the web using aiohttp's ClientSession. ```python import aiohttp import asyncio async def main(): async with aiohttp.ClientSession() as session: async with session.get('http://python.org') as response: print("Status:", response.status) print("Content-type:", response.headers['content-type']) html = await response.text() print("Body:", html[:15], "...") asyncio.run(main()) ``` -------------------------------- ### Changelog Fragment Example Source: https://github.com/aio-libs/aiohttp/blob/master/AGENTS.md Example of how to create a changelog fragment file for a bug fix. ```bash ln -s 1234.bugfix.rst CHANGES/1240.bugfix.rst ``` -------------------------------- ### aiohttp client request example Source: https://github.com/aio-libs/aiohttp/blob/master/docs/http_request_lifecycle.md An example of performing an HTTP GET request using aiohttp, demonstrating the asynchronous nature and session management. ```python async with aiohttp.ClientSession() as session: async with session.get('http://python.org') as response: print(await response.text()) ``` -------------------------------- ### Make a GET Request with aiohttp Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_reference.md This snippet demonstrates how to make a simple GET request to a URL using aiohttp and print the response text. Ensure aiohttp is installed and imported. ```python import aiohttp async def fetch(): async with aiohttp.request('GET', 'http://python.org/') as resp: assert resp.status == 200 print(await resp.text()) ``` -------------------------------- ### Define GET and POST routes Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_reference.md Example of defining GET and POST routes using web.get() and web.post() and adding them to the router. This is a common pattern for setting up basic request handlers. ```python from aiohttp import web async def handle_get(request): ... async def handle_post(request): ... app.router.add_routes([web.get('/get', handle_get), web.post('/post', handle_post), ``` -------------------------------- ### CLI for Serving an Application Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Using the aiohttp.web CLI for quickly serving an Application in development. ```shell $ python -m aiohttp.web -H localhost -P 8080 package.module:init_func ``` -------------------------------- ### Class Based Views Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Demonstrates using class-based views by deriving from aiohttp.web.View. ```python class MyView(web.View): async def get(self): return await get_resp(self.request) async def post(self): return await post_resp(self.request) ``` ```python app.add_routes([web.view('/path/to', MyView)]) ``` ```python @routes.view('/path/to') class MyView(web.View): ... ``` ```python app.router.add_route('*', '/path/to', MyView) ``` -------------------------------- ### Setup aiohttp-debugtoolbar Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_advanced.md This snippet shows how to install and set up the aiohttp-debugtoolbar for development. ```shell pip install aiohttp_debugtoolbar ``` ```python import aiohttp_debugtoolbar from aiohttp_debugtoolbar import toolbar_middleware_factory app = web.Application() aiohttp_debugtoolbar.setup(app) ``` -------------------------------- ### Organizing Handlers in Classes Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Illustrates how to group logically similar handlers into a Python class. ```python async def hello(request): return web.Response(text="Hello, world") app.router.add_get('/', hello) ``` ```python class Handler: def __init__(self): pass async def handle_intro(self, request): return web.Response(text="Hello, world") async def handle_greeting(self, request): name = request.match_info.get('name', "Anonymous") txt = "Hello, {}".format(name) return web.Response(text=txt) handler = Handler() app.add_routes([web.get('/intro', handler.handle_intro), web.get('/greet/{name}', handler.handle_greeting)]) ``` -------------------------------- ### Reverse URL Constructing using Named Resources Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Demonstrates how to define named routes and use them to construct URLs. ```python @routes.get('/root', name='root') async def handler(request): ... ``` ```python url = request.app.router['root'].url_for().with_query({"a": "b", "c": "d"}) assert url == URL('/root?a=b&c=d') ``` -------------------------------- ### Using base_url for multiple requests Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Demonstrates how to use the `base_url` parameter in `ClientSession` for making multiple requests to the same site. ```python async with aiohttp.ClientSession('http://httpbin.org') as session: async with session.get('/get'): pass async with session.post('/post', data=b'data'): pass async with session.put('/put', data=b'data'): pass ``` -------------------------------- ### Application runners Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_advanced.md Example of starting an application using AppRunner and serving HTTP site. ```python runner = web.AppRunner(app) await runner.setup() site = web.TCPSite(runner, 'localhost', 8080) await site.start() while True: await asyncio.sleep(3600) # sleep forever ``` -------------------------------- ### Passing multiple values for the same key Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Demonstrates passing a list of tuples to `params` to specify multiple values for the same key. ```python params = [('key', 'value1'), ('key', 'value2')] async with session.get('http://httpbin.org/get', params=params) as r: expect = 'http://httpbin.org/get?key=value2&key=value1' assert str(r.url) == expect ``` -------------------------------- ### JSON Response Content Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Example of parsing a JSON response directly using the 'json()' method. ```python async with session.get('https://api.github.com/events') as resp: print(await resp.json()) ``` -------------------------------- ### Resource Views Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Shows how to view all registered resources or a subset of named resources in the router. ```python for resource in app.router.resources(): print(resource) ``` ```python for name, resource in app.router.named_resources().items(): print(name, resource) ``` -------------------------------- ### Using Route Decorators Source: https://github.com/aio-libs/aiohttp/blob/master/docs/web_quickstart.md Defining routes using decorators on a RouteTableDef instance. ```python routes = web.RouteTableDef() @routes.get('/') async def get_handler(request): ... @routes.post('/post') async def post_handler(request): ... @routes.put('/put') async def put_handler(request): ... app.add_routes(routes) ``` -------------------------------- ### Streaming upload using a file-like object Source: https://github.com/aio-libs/aiohttp/blob/master/docs/client_quickstart.md Demonstrates streaming a large file to the server by providing a file-like object directly to the 'data' argument. ```python with open("massive-body", "rb") as f: await session.post("https://httpbin.org/post", data=f) ```