Sunrusojsis commited on
Commit
534c2fc
·
verified ·
1 Parent(s): d7af7cc

Create proxy.py

Browse files
Files changed (1) hide show
  1. proxy.py +54 -0
proxy.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import aiohttp
2
+ from aiohttp import web
3
+ from urllib.parse import urlparse
4
+
5
+ async def proxy_handler(request):
6
+ # Retrieve the URL from the query parameters
7
+ target_url = request.query.get('url')
8
+ if not target_url:
9
+ return web.Response(status=400, text="Missing 'url' query parameter.")
10
+
11
+ # Optional: Validate the URL schema
12
+ parsed_url = urlparse(target_url)
13
+ if parsed_url.scheme not in ['http', 'https']:
14
+ return web.Response(status=400, text="Invalid URL scheme. Only HTTP and HTTPS are supported.")
15
+
16
+ # Get the aiohttp ClientSession from the app
17
+ session = request.app['session']
18
+
19
+ # Prepare the request headers, removing the host header
20
+ headers = dict(request.headers)
21
+ headers.pop('Host', None)
22
+
23
+ # Forward the request to the target URL
24
+ async with session.request(
25
+ method=request.method,
26
+ url=target_url,
27
+ headers=headers,
28
+ allow_redirects=False,
29
+ data=await request.read() # Forward the original payload as it is
30
+ ) as response:
31
+ # Prepare the response headers, excluding 'Transfer-Encoding' and 'Content-Encoding'
32
+ response_headers = {k: v for k, v in response.headers.items() if k.lower() not in ['transfer-encoding', 'content-encoding']}
33
+
34
+ # Create a new aiohttp response
35
+ return web.Response(
36
+ status=response.status,
37
+ headers=response_headers,
38
+ body=await response.read()
39
+ )
40
+
41
+ async def create_session(app):
42
+ app['session'] = aiohttp.ClientSession()
43
+
44
+ async def close_session(app):
45
+ await app['session'].close()
46
+
47
+ app = web.Application()
48
+ app.add_routes([web.route('*', '/', proxy_handler)])
49
+
50
+ app.on_startup.append(create_session)
51
+ app.on_cleanup.append(close_session)
52
+
53
+ if __name__ == '__main__':
54
+ web.run_app(app, port=8080) # Specify the port to run on