pycdn/server.py

78 lines
2.4 KiB
Python
Raw Normal View History

2023-03-21 23:58:22 +03:00
from typing import Union, Annotated
2023-03-22 18:22:43 +03:00
import uvicorn
2023-04-06 23:58:56 +03:00
from routes.user_routes import user_route
from bearer.routes.auth import auth
from db.DB import DBException
import mimetypes
from mime.mime import mime_content_type
2023-04-07 16:57:00 +03:00
from fastapi.middleware.cors import CORSMiddleware
2023-03-21 23:58:22 +03:00
2023-04-06 23:58:56 +03:00
from fastapi import FastAPI, File, UploadFile, Form, Response, status, HTTPException
2023-03-21 23:58:22 +03:00
import os
import magic
app = FastAPI()
2023-04-06 23:58:56 +03:00
app.include_router(user_route)
app.include_router(auth)
2023-03-21 23:58:22 +03:00
2023-04-07 16:57:00 +03:00
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
2023-03-21 23:58:22 +03:00
@app.get("/")
def read_root():
return {"Hello": "World"}
2023-04-06 23:58:56 +03:00
@app.get("/items/{name}/{version}/{file}")
2023-03-21 23:58:22 +03:00
def read_item(version: str, name: str, file: str = 'index.js'):
file_path = f"packages/{name}/{version}/{file}"
2023-04-06 23:58:56 +03:00
file_mime = mime_content_type(file_path)
print(file_mime)
2023-03-21 23:58:22 +03:00
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
return Response(content=f.read(), media_type=file_mime)
return status.HTTP_404_NOT_FOUND
@app.post("/files/")
async def create_file(file: Annotated[bytes | None, File()] = None):
if not file:
return {"message": "No file sent"}
else:
return {"file_size": len(file)}
@app.post("/uploadfile/")
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)
2023-04-06 23:58:56 +03:00
dir_last = "packages/{package}/latest".format(package=package)
dir_stable = "packages/{package}/stable".format(package=package)
2023-03-21 23:58:22 +03:00
if not os.path.exists(dir_file):
os.makedirs(dir_file)
2023-04-06 23:58:56 +03:00
if not os.path.exists(dir_last):
os.makedirs(dir_last)
if not os.path.exists(dir_stable):
os.makedirs(dir_stable)
2023-03-21 23:58:22 +03:00
with open(f"{dir_file}/{filename}", 'wb') as f:
f.write(contents)
2023-04-06 23:58:56 +03:00
with open(f"{dir_last}/{filename}", 'wb') as f:
f.write(contents)
2023-03-23 00:36:10 +03:00
except Exception as err:
return {"message": "There was an error uploading the file, error {err}".format(err=err)}
2023-03-21 23:58:22 +03:00
finally:
file.file.close()
2023-03-22 18:22:43 +03:00
return {"message": f"Successfully uploaded {file.filename}"}
if __name__ == "__main__":
2023-03-23 00:36:10 +03:00
uvicorn.run("server:app", port=5044, log_level="info")