Here is a very basic “proxy”. It does not pass along any headers or cookies, but you could apply the same principal I laid out below to do it.
from sanic import Sanic
from sanic.response import text, html, json
import aiohttp
app = Sanic()
@app.get("/text")
async def response_text(request):
return text("foo")
@app.get("/html")
async def response_html(request):
return html("<html><body><h1>Hello, world.</h1></body></html>")
@app.get("/json")
async def response_json(request):
return json({"foo": "bar"})
@app.get("/bad")
async def response_bad(request):
return text("bad", status=400)
@app.get("/proxy/<location>")
async def response_proxy(request, location):
url = f"http://localhost:8000/{location}"
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
status = resp.status
if resp.content_type == "application/json":
func = json
body = await resp.json()
elif resp.content_type == "text/html":
func = html
body = await resp.text()
else:
func = text
body = await resp.text()
return func(body, status=status)
if __name__ == "__main__":
app.run(debug=True)
Here are some results of hitting the /proxy/<location>
endpoint:
â•─adam@thebrewery ~
╰─$ curl localhost:8000/proxy/text -i
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 3
Content-Type: text/plain; charset=utf-8
foo
â•─adam@thebrewery ~
╰─$ curl localhost:8000/proxy/html -i
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 48
Content-Type: text/html; charset=utf-8
<html><body><h1>Hello, world.</h1></body></html>
â•─adam@thebrewery ~
╰─$ curl localhost:8000/proxy/bad -i
HTTP/1.1 400 Bad Request
Connection: keep-alive
Keep-Alive: 5
Content-Length: 3
Content-Type: text/plain; charset=utf-8
bad
â•─adam@thebrewery ~
╰─$ curl localhost:8000/proxy/json -i
HTTP/1.1 200 OK
Connection: keep-alive
Keep-Alive: 5
Content-Length: 13
Content-Type: application/json
{"foo":"bar"}
@smlbiobot is this sort of what you had in mind?