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
+ )
3
18
import shutil
4
19
import os
5
20
import json
6
21
from pathlib import Path
7
- from fastapi import FastAPI
8
22
from fastapi .templating import Jinja2Templates
9
23
from fastapi .middleware .cors import CORSMiddleware
10
24
from slowapi .errors import RateLimitExceeded
16
30
from pygments .lexers import get_lexer_by_name , guess_lexer
17
31
from pygments .formatters import HtmlFormatter
18
32
from pygments .util import ClassNotFound
19
- from typing import List , Optional , Any
33
+ from typing import List , Optional
20
34
21
35
limiter = Limiter (key_func = get_remote_address )
22
36
app : FastAPI = FastAPI (title = "paste.py 🐍" )
41
55
42
56
BASE_DIR : Path = Path (__file__ ).resolve ().parent
43
57
44
- templates : Jinja2Templates = Jinja2Templates (
45
- directory = str (Path (BASE_DIR , "templates" )))
58
+ templates : Jinja2Templates = Jinja2Templates (directory = str (Path (BASE_DIR , "templates" )))
46
59
47
60
48
61
@app .post ("/file" )
49
62
@limiter .limit ("100/minute" )
50
- async def post_as_a_file (request : Request , file : UploadFile = File (...)) -> PlainTextResponse :
63
+ async def post_as_a_file (
64
+ request : Request , file : UploadFile = File (...)
65
+ ) -> PlainTextResponse :
51
66
try :
52
67
uuid : str = generate_uuid ()
53
68
if uuid in large_uuid_storage :
54
69
uuid = generate_uuid ()
55
70
# Extract file extension from the filename
56
71
try :
57
- file_extension : str = Path (file .filename ).suffix [1 :]
58
- path : str = f"data/{ uuid } .{ file_extension } "
72
+ file_extension : Optional [str ] = None
73
+ if file .filename is not None :
74
+ file_extension = Path (file .filename ).suffix [1 :]
75
+ path : str = f"data/{ uuid } { file_extension } "
59
76
except Exception :
60
77
path = f"data/{ uuid } "
61
78
finally :
62
79
val : str = "/" .join (path .split ("/" )[1 :])
63
80
with open (path , "wb" ) as f :
64
81
shutil .copyfileobj (file .file , f )
65
82
large_uuid_storage .append (uuid )
66
- print (large_uuid_storage )
67
83
except Exception :
68
84
raise HTTPException (
69
85
detail = "There was an error uploading the file" ,
@@ -75,7 +91,9 @@ async def post_as_a_file(request: Request, file: UploadFile = File(...)) -> Plai
75
91
76
92
77
93
@app .get ("/paste/{uuid}" )
78
- async def get_paste_data (uuid : str , user_agent : Optional [str ] = Header (None )) -> Any :
94
+ async def get_paste_data (
95
+ uuid : str , user_agent : Optional [str ] = Header (None )
96
+ ) -> Response :
79
97
path : str = f"data/{ uuid } "
80
98
try :
81
99
with open (path , "rb" ) as f :
@@ -97,13 +115,11 @@ async def get_paste_data(uuid: str, user_agent: Optional[str] = Header(None)) ->
97
115
try :
98
116
lexer = get_lexer_by_name (file_extension , stripall = True )
99
117
except ClassNotFound :
100
- lexer = get_lexer_by_name (
101
- "text" , stripall = True ) # Default lexer
118
+ lexer = get_lexer_by_name ("text" , stripall = True ) # Default lexer
102
119
formatter = HtmlFormatter (
103
- style = "colorful" , full = True , linenos = "inline" , cssclass = 'code' )
120
+ style = "colorful" , full = True , linenos = "inline" , cssclass = "code"
121
+ )
104
122
highlighted_code : str = highlight (content , lexer , formatter )
105
-
106
- print (highlighted_code )
107
123
custom_style = """
108
124
.code pre span.linenos {
109
125
color: #999;
@@ -154,19 +170,16 @@ async def get_paste_data(uuid: str, user_agent: Optional[str] = Header(None)) ->
154
170
</body>
155
171
</html>
156
172
"""
157
- return HTMLResponse (
158
- content = response_content
159
- )
160
- except Exception as e :
161
- print (e )
173
+ return HTMLResponse (content = response_content )
174
+ except Exception :
162
175
raise HTTPException (
163
176
detail = "404: The Requested Resource is not found" ,
164
177
status_code = status .HTTP_404_NOT_FOUND ,
165
178
)
166
179
167
180
168
181
@app .get ("/" , response_class = HTMLResponse )
169
- async def indexpage (request : Request ) -> HTMLResponse :
182
+ async def indexpage (request : Request ) -> Response :
170
183
return templates .TemplateResponse ("index.html" , {"request" : request })
171
184
172
185
@@ -187,7 +200,7 @@ async def delete_paste(uuid: str) -> PlainTextResponse:
187
200
188
201
189
202
@app .get ("/web" , response_class = HTMLResponse )
190
- async def web (request : Request ) -> HTMLResponse :
203
+ async def web (request : Request ) -> Response :
191
204
return templates .TemplateResponse ("web.html" , {"request" : request })
192
205
193
206
@@ -209,8 +222,7 @@ async def web_post(
209
222
with open (path , "wb" ) as f :
210
223
f .write (file_content )
211
224
large_uuid_storage .append (uuid_ )
212
- except Exception as e :
213
- print (e )
225
+ except Exception :
214
226
raise HTTPException (
215
227
detail = "There was an error uploading the file" ,
216
228
status_code = status .HTTP_403_FORBIDDEN ,
0 commit comments