Skip to content

Instantly share code, notes, and snippets.

@nilleb
Created July 11, 2022 19:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilleb/d42fcabc03cec74a665bd53f9d8eaa08 to your computer and use it in GitHub Desktop.
Save nilleb/d42fcabc03cec74a665bd53f9d8eaa08 to your computer and use it in GitHub Desktop.
CORS proxy
# -*- coding: utf-8 -*-
# forwards the calls to http://localhost:8000/https://google.com to https://google.com - copying the headers, query strings, etc
from fastapi import FastAPI, Request, Response
from fastapi.middleware.cors import CORSMiddleware
import requests
app = FastAPI()
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
method_requests_mapping = {
"GET": requests.get,
"HEAD": requests.head,
"POST": requests.post,
"PUT": requests.put,
"DELETE": requests.delete,
"PATCH": requests.patch,
"OPTIONS": requests.options,
}
# @app.api_route("/{path_name:path}", methods=["GET"])
@app.api_route("/{path_name:path}", methods=method_requests_mapping.keys())
async def proxy(request: Request, path_name: str):
requests_function = method_requests_mapping[request.method]
body = b""
async for chunk in request.stream():
body += chunk
url = f"{path_name}?{request.query_params}"
headers = {key: value for key, value in request.headers.items() if key != "host"}
outgoing_request = requests_function(url, stream=True, data=body, headers=headers)
response = Response(
outgoing_request.content, status_code=outgoing_request.status_code
)
response.headers["Access-Control-Allow-Origin"] = "*"
return response
fastapi
uvicorn[standard]
requests
uvicorn proxy:app --reload
# set -euo pipefail
python3 -m venv venv
. venv/bin/activate
python -m pip install -r equirements.txt
pushd venv/bin
python_interpreter_path=`pwd`
echo $python_interpreter_path/python
popd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment