Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_cors_vary_header_defaults_to_origin():
app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=["https://example.org"])
headers = {"Origin": "https://example.org"}
@app.route("/")
def homepage(request):
return PlainTextResponse("Homepage", status_code=200)
client = TestClient(app)
response = client.get("/", headers=headers)
assert response.status_code == 200
assert response.headers["vary"] == "Origin"
from app.api.api_v1.api import api_router
from app.core import config
app = FastAPI(title=config.PROJECT_NAME, openapi_url="/api/v1/openapi.json")
# CORS
origins = []
# Set all CORS enabled origins
if config.BACKEND_CORS_ORIGINS:
origins_raw = config.BACKEND_CORS_ORIGINS.split(",")
for origin in origins_raw:
use_origin = origin.strip()
origins.append(use_origin)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
),
app.include_router(api_router, prefix=config.API_V1_STR)
api = FastAPI(title=config.API_PROJECT_NAME, openapi_url="/api/v1/openapi.json")
origins = []
# Set all CORS enabled origins
if config.API_CORS_ORIGINS:
origins_raw = config.API_CORS_ORIGINS.split(",")
for origin in origins_raw:
use_origin = origin.strip()
origins.append(use_origin)
logger.info(f"global@api.py - Registering cors origins {origins}")
api.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
),
main_router = APIRouter()
for r, ropts in routers:
logger.debug(f"global@api.py - Registering router {str(r)} {str(ropts)}")
main_router.include_router(r, **ropts)
logger.debug(f"global@api.py - Registering main router {str(r)} {str(ropts)}")
api.include_router(main_router, prefix=config.API_V1_STR)
def get_application() -> FastAPI:
application = FastAPI(title="Haystack-API", debug=True, version="0.1")
application.add_middleware(
CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"],
)
if APM_SERVER:
apm_config = {"SERVICE_NAME": APM_SERVICE_NAME, "SERVER_URL": APM_SERVER, "CAPTURE_BODY": "all"}
elasticapm = make_apm_client(apm_config)
application.add_middleware(ElasticAPM, client=elasticapm)
application.add_exception_handler(HTTPException, http_error_handler)
application.include_router(api_router)
return application
from fastai import *
from fastai.vision import *
from io import BytesIO
from starlette.applications import Starlette
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import HTMLResponse, JSONResponse
from starlette.staticfiles import StaticFiles
export_file_url = 'https://www.dropbox.com/s/6bgq8t6yextloqp/export.pkl?raw=1'
export_file_name = 'export.pkl'
classes = ['black', 'grizzly', 'teddys']
path = Path(__file__).parent
app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
app.mount('/static', StaticFiles(directory='app/static'))
async def download_file(url, dest):
if dest.exists(): return
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.read()
with open(dest, 'wb') as f:
f.write(data)
async def setup_learner():
await download_file(export_file_url, path / export_file_name)
try:
learn = load_learner(path, export_file_name)
modelTypes = {
"resnet18": models.resnet18,
"resnet34": models.resnet34,
"resnet50": models.resnet50,
"resnet101": models.resnet101,
"resnet152": models.resnet152,
}
path = Path(__file__).parent
with open("modelDefinition.json") as f:
modelDefs = json.load(f)
app = Starlette()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_headers=["X-Requested-With", "Content-Type"],
)
app.mount("/static", StaticFiles(directory="app/static"))
async def download_file(url, dest):
if dest.exists():
return
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
print("Downloading from " + url)
data = await response.read()
with open(dest, "wb") as f:
f.write(data)
print("File written to " + str(dest))
[CORSMiddleware]: https://www.starlette.io/middleware/#corsmiddleware
Settings:
- `CORS` (bool or dict):
if `True`, the default configuration defined in [constants.py] is used.
Otherwise, the dictionary is passed to Starlette's [CORSMiddleware].
"""
cors: typing.Optional[typing.Union[bool, dict]] = settings.get("CORS")
if cors is None:
return
if cors is True:
cors = dict(DEFAULT_CORS_CONFIG)
app.add_middleware(CORSMiddleware, **cors)
from starlette.responses import HTMLResponse, JSONResponse
from starlette.staticfiles import StaticFiles
from starlette.middleware.cors import CORSMiddleware
import uvicorn, aiohttp, asyncio
from io import BytesIO
from config import config
from fastai.text import *
path = Path(__file__).parent
id_to_col = []
setup_done = False
learn = None
app = Starlette()
app.add_middleware(CORSMiddleware, allow_origins=['*'], allow_headers=['X-Requested-With', 'Content-Type'])
app.mount('/static', StaticFiles(directory=path/'static'))
async def download_file(url, dest):
if dest.exists(): return
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.read()
with open(dest, 'wb') as f: f.write(data)
async def setup_learner():
global learn
await download_file(config.model_file_url, path/'models'/f'{config.model_file_name}')
await download_file(config.data_file_url, path /'data'/ f'{config.data_file_name}')
await download_file(config.vocabulary_file_url, path /'data'/ f'{config.vocabulary_file_name}')
await download_file(config.id_to_col_url , path / 'data' / f'{config.id_to_col_file_name}')
with open(path / 'data'/ f'{config.vocabulary_file_name}', 'rb') as f:
# img_src = "http://127.0.0.1/static/{chord}/{variation}.png"
# response = json.dumps({"type": "chord.hover", "img_src": img_src})
# return response
@app.on_event("startup")
async def startup():
await database.connect()
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])