Created
April 30, 2019 16:23
-
-
Save nobbynobbs/fb58e0fcc838ef86e0adf4df8c33ef20 to your computer and use it in GitHub Desktop.
aiohttp-server-and-session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aiohttp import web, ClientSession | |
from aiohttp.web import middleware | |
async def search(request): | |
q = request.query.get("q", "") | |
session = request.app["client_session"] | |
async with session.get("https://ya.ru", params={"q": q}) as request: | |
body = await request.read() | |
return web.Response(body=body, headers={"content-type": "text/html"}) | |
async def client_session(app): | |
app["client_session"] = ClientSession() | |
yield | |
await app["client_session"].close() | |
def get_app(): | |
app = web.Application(middlewares=[web.normalize_path_middleware()]) | |
app.add_routes([ | |
web.get('/', search) | |
]) | |
app.cleanup_ctx.append(client_session) | |
return app | |
def main(): | |
app = get_app() | |
web.run_app(app) | |
if __name__ == "__main__": | |
"""enter http://127.0.0.1:8080/?q=aiohttp&lr=47 in browser""" | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment