|
1 | | -from fastapi import File, UploadFile, HTTPException, status, Request, Form, FastAPI |
| 1 | +from fastapi import File, UploadFile, HTTPException, status, Request, Form, FastAPI, Header |
2 | 2 | from fastapi.responses import PlainTextResponse, HTMLResponse, RedirectResponse, JSONResponse |
3 | 3 | import shutil |
4 | 4 | import os |
|
16 | 16 | from pygments.lexers import get_lexer_by_name, guess_lexer |
17 | 17 | from pygments.formatters import HtmlFormatter |
18 | 18 | from pygments.util import ClassNotFound |
19 | | -from typing import List, Optional |
| 19 | +from typing import List, Optional, Any |
20 | 20 |
|
21 | 21 | limiter = Limiter(key_func=get_remote_address) |
22 | 22 | app: FastAPI = FastAPI(title="paste.py 🐍") |
@@ -74,11 +74,18 @@ async def post_as_a_file(request: Request, file: UploadFile = File(...)) -> Plai |
74 | 74 |
|
75 | 75 |
|
76 | 76 | @app.get("/paste/{uuid}") |
77 | | -async def get_paste_data(uuid: str) -> HTMLResponse: |
| 77 | +async def get_paste_data(uuid: str, user_agent: Optional[str] = Header(None)) -> Any: |
78 | 78 | path: str = f"data/{uuid}" |
79 | 79 | try: |
80 | 80 | with open(path, "rb") as f: |
81 | 81 | content: str = f.read().decode("utf-8") |
| 82 | + # Check if the request is from a browser |
| 83 | + is_browser_request = "Mozilla" in user_agent if user_agent else False |
| 84 | + |
| 85 | + if not is_browser_request: |
| 86 | + # Return plain text response |
| 87 | + return PlainTextResponse(content) |
| 88 | + |
82 | 89 | # Get file extension from the filename |
83 | 90 | file_extension: str = Path(path).suffix[1:] |
84 | 91 | if file_extension == "": |
|
0 commit comments