1- from fastapi import File , UploadFile , HTTPException , status , Request , Form , FastAPI , Header
2- from fastapi .responses import PlainTextResponse , HTMLResponse , RedirectResponse , JSONResponse
1+ from fastapi import (
2+ File ,
3+ UploadFile ,
4+ HTTPException ,
5+ status ,
6+ Request ,
7+ Form ,
8+ FastAPI ,
9+ Header ,
10+ Response ,
11+ )
12+ from fastapi .responses import (
13+ PlainTextResponse ,
14+ HTMLResponse ,
15+ RedirectResponse ,
16+ JSONResponse ,
17+ )
318import shutil
419import os
520import json
621from pathlib import Path
7- from fastapi import FastAPI
822from fastapi .templating import Jinja2Templates
923from fastapi .middleware .cors import CORSMiddleware
1024from slowapi .errors import RateLimitExceeded
1630from pygments .lexers import get_lexer_by_name , guess_lexer
1731from pygments .formatters import HtmlFormatter
1832from pygments .util import ClassNotFound
19- from typing import List , Optional , Any
33+ from typing import List , Optional
34+ from . import __version__ , __author__ , __contact__ , __url__
35+
36+ description : str = "paste.py π - A pastebin written in python."
2037
2138limiter = Limiter (key_func = get_remote_address )
22- app : FastAPI = FastAPI (title = "paste.py π" )
39+ app : FastAPI = FastAPI (
40+ title = "paste.py π" ,
41+ version = __version__ ,
42+ contact = dict (
43+ name = __author__ ,
44+ url = __url__ ,
45+ email = __contact__ ,
46+ ),
47+ license_info = dict (name = "MIT" , url = "https://opensource.org/license/mit/" ),
48+ openapi_url = None ,
49+ docs_url = None ,
50+ redoc_url = None ,
51+ )
2352app .state .limiter = limiter
2453app .add_exception_handler (RateLimitExceeded , _rate_limit_exceeded_handler )
2554
4170
4271BASE_DIR : Path = Path (__file__ ).resolve ().parent
4372
44- templates : Jinja2Templates = Jinja2Templates (
45- directory = str (Path (BASE_DIR , "templates" )))
73+ templates : Jinja2Templates = Jinja2Templates (directory = str (Path (BASE_DIR , "templates" )))
4674
4775
4876@app .post ("/file" )
@@ -54,16 +82,17 @@ async def post_as_a_file(request: Request, file: UploadFile = File(...)) -> Plai
5482 uuid = generate_uuid ()
5583 # Extract file extension from the filename
5684 try :
57- file_extension : str = Path (file .filename ).suffix [1 :]
58- path : str = f"data/{ uuid } .{ file_extension } "
85+ file_extension : Optional [str ] = None
86+ if file .filename is not None :
87+ file_extension = Path (file .filename ).suffix [1 :]
88+ path : str = f"data/{ uuid } { file_extension } "
5989 except Exception :
6090 path = f"data/{ uuid } "
6191 finally :
6292 val : str = "/" .join (path .split ("/" )[1 :])
6393 with open (path , "wb" ) as f :
6494 shutil .copyfileobj (file .file , f )
6595 large_uuid_storage .append (uuid )
66- print (large_uuid_storage )
6796 except Exception :
6897 raise HTTPException (
6998 detail = "There was an error uploading the file" ,
@@ -75,7 +104,7 @@ async def post_as_a_file(request: Request, file: UploadFile = File(...)) -> Plai
75104
76105
77106@app .get ("/paste/{uuid}" )
78- async def get_paste_data (uuid : str , user_agent : Optional [str ] = Header (None )) -> Any :
107+ async def get_paste_data (uuid : str , user_agent : Optional [str ] = Header (None )) -> Response :
79108 path : str = f"data/{ uuid } "
80109 try :
81110 with open (path , "rb" ) as f :
@@ -97,10 +126,8 @@ async def get_paste_data(uuid: str, user_agent: Optional[str] = Header(None)) ->
97126 try :
98127 lexer = get_lexer_by_name (file_extension , stripall = True )
99128 except ClassNotFound :
100- lexer = get_lexer_by_name (
101- "text" , stripall = True ) # Default lexer
102- formatter = HtmlFormatter (
103- style = "colorful" , full = True , linenos = "inline" , cssclass = 'code' )
129+ lexer = get_lexer_by_name ("text" , stripall = True ) # Default lexer
130+ formatter = HtmlFormatter (style = "colorful" , full = True , linenos = "inline" , cssclass = "code" )
104131 highlighted_code : str = highlight (content , lexer , formatter )
105132 # print(highlighted_code)
106133 custom_style = """
@@ -194,19 +221,16 @@ async def get_paste_data(uuid: str, user_agent: Optional[str] = Header(None)) ->
194221 </script>
195222 </html>
196223 """
197- return HTMLResponse (
198- content = response_content
199- )
200- except Exception as e :
201- print (e )
224+ return HTMLResponse (content = response_content )
225+ except Exception :
202226 raise HTTPException (
203227 detail = "404: The Requested Resource is not found" ,
204228 status_code = status .HTTP_404_NOT_FOUND ,
205229 )
206230
207231
208232@app .get ("/" , response_class = HTMLResponse )
209- async def indexpage (request : Request ) -> HTMLResponse :
233+ async def indexpage (request : Request ) -> Response :
210234 return templates .TemplateResponse ("index.html" , {"request" : request })
211235
212236
@@ -217,25 +241,19 @@ async def delete_paste(uuid: str) -> PlainTextResponse:
217241 os .remove (path )
218242 return PlainTextResponse (f"File successfully deleted { uuid } " )
219243 except FileNotFoundError :
220- raise HTTPException (
221- detail = "File Not Found" , status_code = status .HTTP_404_NOT_FOUND
222- )
244+ raise HTTPException (detail = "File Not Found" , status_code = status .HTTP_404_NOT_FOUND )
223245 except Exception as e :
224- raise HTTPException (
225- detail = f"The exception is { e } " , status_code = status .HTTP_409_CONFLICT
226- )
246+ raise HTTPException (detail = f"The exception is { e } " , status_code = status .HTTP_409_CONFLICT )
227247
228248
229249@app .get ("/web" , response_class = HTMLResponse )
230- async def web (request : Request ) -> HTMLResponse :
250+ async def web (request : Request ) -> Response :
231251 return templates .TemplateResponse ("web.html" , {"request" : request })
232252
233253
234254@app .post ("/web" , response_class = PlainTextResponse )
235255@limiter .limit ("100/minute" )
236- async def web_post (
237- request : Request , content : str = Form (...), extension : Optional [str ] = Form (None )
238- ) -> RedirectResponse :
256+ async def web_post (request : Request , content : str = Form (...), extension : Optional [str ] = Form (None )) -> RedirectResponse :
239257 try :
240258 file_content : bytes = content .encode ()
241259 uuid : str = generate_uuid ()
@@ -249,16 +267,13 @@ async def web_post(
249267 with open (path , "wb" ) as f :
250268 f .write (file_content )
251269 large_uuid_storage .append (uuid_ )
252- except Exception as e :
253- print (e )
270+ except Exception :
254271 raise HTTPException (
255272 detail = "There was an error uploading the file" ,
256273 status_code = status .HTTP_403_FORBIDDEN ,
257274 )
258275
259- return RedirectResponse (
260- f"{ BASE_URL } /paste/{ uuid_ } " , status_code = status .HTTP_303_SEE_OTHER
261- )
276+ return RedirectResponse (f"{ BASE_URL } /paste/{ uuid_ } " , status_code = status .HTTP_303_SEE_OTHER )
262277
263278
264279@app .get ("/health" , status_code = status .HTTP_200_OK )
0 commit comments