1- from fastapi import File , UploadFile , HTTPException , status , Request , Form
1+ from fastapi import File , UploadFile , HTTPException , status , Request , Form , FastAPI
22from fastapi .responses import PlainTextResponse , HTMLResponse , RedirectResponse , JSONResponse
33import shutil
44import os
1616from pygments .lexers import get_lexer_by_name , guess_lexer
1717from pygments .formatters import HtmlFormatter
1818from pygments .util import ClassNotFound
19+ from typing import List , Optional
1920
2021limiter = Limiter (key_func = get_remote_address )
21- app = FastAPI (title = "paste.py 🐍" )
22+ app : FastAPI = FastAPI (title = "paste.py 🐍" )
2223app .state .limiter = limiter
2324app .add_exception_handler (RateLimitExceeded , _rate_limit_exceeded_handler )
2425
25- origins = ["*" ]
26+ origins : List [ str ] = ["*" ]
2627
27- BASE_URL = r"http://paste.fosscu.org"
28+ BASE_URL : str = r"http://paste.fosscu.org"
2829
2930app .add_middleware (
3031 CORSMiddleware ,
3637
3738app .add_middleware (LimitUploadSize , max_upload_size = 20_000_000 ) # ~20MB
3839
39- large_uuid_storage = []
40+ large_uuid_storage : List [ str ] = []
4041
41- BASE_DIR = Path (__file__ ).resolve ().parent
42+ BASE_DIR : Path = Path (__file__ ).resolve ().parent
4243
43- templates = Jinja2Templates (directory = str (Path (BASE_DIR , "templates" )))
44+ templates : Jinja2Templates = Jinja2Templates (directory = str (Path (BASE_DIR , "templates" )))
4445
4546
4647@app .post ("/file" )
4748@limiter .limit ("100/minute" )
48- async def post_as_a_file (request : Request , file : UploadFile = File (...)):
49+ async def post_as_a_file (request : Request , file : UploadFile = File (...)) -> PlainTextResponse :
4950 try :
50- uuid = generate_uuid ()
51+ uuid : str = generate_uuid ()
5152 if uuid in large_uuid_storage :
5253 uuid = generate_uuid ()
5354 # Extract file extension from the filename
5455 try :
55- file_extension = Path (file .filename ).suffix [1 :]
56- path = f"data/{ uuid } .{ file_extension } "
56+ file_extension : str = Path (file .filename ).suffix [1 :]
57+ path : str = f"data/{ uuid } .{ file_extension } "
5758 except Exception :
5859 path = f"data/{ uuid } "
5960 finally :
60- val = "/" .join (path .split ("/" )[1 :])
61+ val : str = "/" .join (path .split ("/" )[1 :])
6162 with open (path , "wb" ) as f :
6263 shutil .copyfileobj (file .file , f )
6364 large_uuid_storage .append (uuid )
6465 print (large_uuid_storage )
6566 except Exception :
66- # return {"message": "There was an error uploading the file"}
6767 raise HTTPException (
6868 detail = "There was an error uploading the file" ,
6969 status_code = status .HTTP_403_FORBIDDEN ,
@@ -74,13 +74,13 @@ async def post_as_a_file(request: Request, file: UploadFile = File(...)):
7474
7575
7676@app .get ("/paste/{uuid}" )
77- async def get_paste_data (uuid ) :
78- path = f"data/{ uuid } "
77+ async def get_paste_data (uuid : str ) -> HTMLResponse :
78+ path : str = f"data/{ uuid } "
7979 try :
8080 with open (path , "rb" ) as f :
81- content = f .read ().decode ("utf-8" )
81+ content : str = f .read ().decode ("utf-8" )
8282 # Get file extension from the filename
83- file_extension = Path (path ).suffix [1 :]
83+ file_extension : str = Path (path ).suffix [1 :]
8484 if file_extension == "" :
8585 # Guess lexer based on content
8686 lexer = guess_lexer (content )
@@ -93,7 +93,7 @@ async def get_paste_data(uuid):
9393 "text" , stripall = True ) # Default lexer
9494 formatter = HtmlFormatter (
9595 style = "colorful" , full = True , linenos = "inline" )
96- highlighted_code = highlight (content , lexer , formatter )
96+ highlighted_code : str = highlight (content , lexer , formatter )
9797 return HTMLResponse (
9898 content = highlighted_code
9999 )
@@ -106,13 +106,13 @@ async def get_paste_data(uuid):
106106
107107
108108@app .get ("/" , response_class = HTMLResponse )
109- async def indexpage (request : Request ):
109+ async def indexpage (request : Request ) -> HTMLResponse :
110110 return templates .TemplateResponse ("index.html" , {"request" : request })
111111
112112
113113@app .delete ("/paste/{uuid}" , response_class = PlainTextResponse )
114- async def delete_paste (uuid ) :
115- path = f"data/{ uuid } "
114+ async def delete_paste (uuid : str ) -> PlainTextResponse :
115+ path : str = f"data/{ uuid } "
116116 try :
117117 os .remove (path )
118118 return PlainTextResponse (f"File successfully deleted { uuid } " )
@@ -127,23 +127,25 @@ async def delete_paste(uuid):
127127
128128
129129@app .get ("/web" , response_class = HTMLResponse )
130- async def web (request : Request ):
130+ async def web (request : Request ) -> HTMLResponse :
131131 return templates .TemplateResponse ("web.html" , {"request" : request })
132132
133133
134134@app .post ("/web" , response_class = PlainTextResponse )
135135@limiter .limit ("100/minute" )
136- async def web_post (request : Request , content : str = Form (...), extension : str = Form (None )):
136+ async def web_post (
137+ request : Request , content : str = Form (...), extension : Optional [str ] = Form (None )
138+ ) -> RedirectResponse :
137139 try :
138- file_content = content .encode ()
139- uuid = generate_uuid ()
140+ file_content : bytes = content .encode ()
141+ uuid : str = generate_uuid ()
140142 if uuid in large_uuid_storage :
141143 uuid = generate_uuid ()
142144 if extension :
143145 uuid_ = uuid + extension
144146 else :
145147 uuid_ = uuid
146- path = f"data/{ uuid_ } "
148+ path : str = f"data/{ uuid_ } "
147149 with open (path , "wb" ) as f :
148150 f .write (file_content )
149151 large_uuid_storage .append (uuid_ )
@@ -165,11 +167,10 @@ async def health() -> dict[str, str]:
165167
166168
167169@app .get ("/languages.json" , response_class = JSONResponse )
168- async def get_languages ():
170+ async def get_languages () -> JSONResponse :
169171 try :
170172 with open (Path (BASE_DIR , "languages.json" ), "r" ) as file :
171- languages_data = json .load (file )
172- # print(languages_data)
173+ languages_data : dict = json .load (file )
173174 return JSONResponse (content = languages_data , status_code = status .HTTP_200_OK )
174175 except FileNotFoundError :
175176 raise HTTPException (
0 commit comments