From 2a1c24cda13d06632aa96212b09938fcb7db715d Mon Sep 17 00:00:00 2001 From: Kavalar Date: Sun, 9 Apr 2023 14:26:34 +0300 Subject: [PATCH] cors --- server.py | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/server.py b/server.py index bc35ae9..8af7162 100644 --- a/server.py +++ b/server.py @@ -5,38 +5,52 @@ from bearer.routes.auth import auth from db.DB import DBException import mimetypes from mime.mime import mime_content_type -from fastapi.middleware.cors import CORSMiddleware +from starlette.middleware import Middleware +from starlette.middleware.cors import CORSMiddleware from fastapi import FastAPI, File, UploadFile, Form, Response, status, HTTPException import os import magic -app = FastAPI() +middleware = [ + Middleware( + CORSMiddleware, + allow_origins=['*'], + allow_credentials=True, + allow_methods=['*'], + allow_headers=['*'] + ) +] + +app = FastAPI(middleware=middleware) + +# app.add_middleware( +# CORSMiddleware, +# allow_origins=['*'], +# allow_credentials=True, +# allow_methods=['*'], +# allow_headers=['*'], +# max_age=3600 +# ) + app.include_router(user_route) app.include_router(auth) -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) @app.get("/") -def read_root(): +async def read_root(): return {"Hello": "World"} @app.get("/items/{name}/{version}/{file}") -def read_item(version: str, name: str, file: str = 'index.js'): +async def read_item(version: str, name: str, file: str = 'index.js'): file_path = f"packages/{name}/{version}/{file}" file_mime = mime_content_type(file_path) print(file_mime) if os.path.exists(file_path): with open(file_path, 'rb') as f: - return Response(content=f.read(), media_type=file_mime) + return Response(content=f.read(), media_type=file_mime, headers={"Access-Control-Allow-Origin": "*"}) return status.HTTP_404_NOT_FOUND @@ -50,7 +64,8 @@ async def create_file(file: Annotated[bytes | None, File()] = None): @app.post("/uploadfile/") -async def create_upload_file(file: UploadFile | None, package: Annotated[str, Form()], version: Annotated[str, Form()], filename: Annotated[str, Form()]): +async def create_upload_file(file: UploadFile | None, package: Annotated[str, Form()], version: Annotated[str, Form()], + filename: Annotated[str, Form()]): try: contents = file.file.read() dir_file = "packages/{package}/{version}".format(package=package, version=version) @@ -75,4 +90,4 @@ async def create_upload_file(file: UploadFile | None, package: Annotated[str, Fo if __name__ == "__main__": - uvicorn.run("server:app", port=5044, log_level="info") \ No newline at end of file + uvicorn.run("server:app", port=5044, log_level="info")