SHARE
TWEET

Untitled

a guest Dec 11th, 2019 91 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from aiohttp import web
  2. import aiohttp
  3. import yarl
  4.  
  5.  
  6. async def proxy_handler(request: web.Request) -> web.Response:
  7.     """
  8.    Check request contains http url in query args:
  9.        /fetch?url=http%3A%2F%2Fexample.com%2F
  10.    and trying to fetch it and return body with http status.
  11.    If url passed without scheme or is invalid raise 400 Bad request.
  12.    On failure raise 502 Bad gateway.
  13.    :param request: aiohttp.web.Request to handle
  14.    :return: aiohttp.web.Response
  15.    """
  16.     url = yarl.URL(request.url).query.get('url')
  17.     url_scheme = yarl.URL(url).scheme if url else None
  18.     error_status = 400
  19.     if not url:
  20.         text, status = 'No url to fetch', error_status
  21.     elif not url_scheme:
  22.         text, status = 'Empty url scheme', error_status
  23.     elif url_scheme != 'http':
  24.         text, status = 'Bad url scheme: {}'.format(yarl.URL(url).scheme), error_status
  25.     else:
  26.         async with request.app['session'] as session:
  27.             response = await session.get(url)
  28.             text, status = await response.text(), response.status
  29.     return web.Response(text=text, status=status)
  30.  
  31.  
  32. async def setup_application(app: web.Application) -> None:
  33.     """
  34.    Setup application routes and aiohttp session for fetching
  35.    :param app: app to apply settings with
  36.    """
  37.     app['session'] = aiohttp.ClientSession()
  38.     app.router.add_get('/fetch', proxy_handler)
  39.  
  40.  
  41. async def teardown_application(app: web.Application) -> None:
  42.     """
  43.    Application with aiohttp session for tearing down
  44.    :param app: app for tearing down
  45.    """
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top