Skip to content

Commit 8913648

Browse files
fix head requests
1 parent a9a41a0 commit 8913648

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

app.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ async def fetch_data(url):
160160
else:
161161
return f"Request failed with status code {response.status}"
162162

163-
@app.route("/", methods=["GET"])
163+
@app.get("/", response_class=HTMLResponse)
164164
async def home(request: Request):
165165
"""Render the home page with form."""
166166
return templates.TemplateResponse("create_redirect.html", {
@@ -170,7 +170,7 @@ async def home(request: Request):
170170
"errors": {} # No errors initially
171171
})
172172

173-
@app.route("/", methods=["POST"])
173+
@app.post("/", response_class=HTMLResponse)
174174
async def create_redirect(request: Request, code: str = Form(...), password: str = Form(...)):
175175
"""Handle form submission, hash password, generate random key, and store redirect info in MongoDB."""
176176

@@ -206,7 +206,33 @@ async def create_redirect(request: Request, code: str = Form(...), password: str
206206

207207
import traceback
208208

209-
@app.route("/redirect/{key}", methods=["GET", "HEAD"])
209+
@app.get("/redirect/{key}", response_class=HTMLResponse)
210+
async def dynamic_redirect(request: Request, key: str):
211+
"""Dynamically handle redirects based on MongoDB data."""
212+
collection = db.route_handlers
213+
document = await collection.find_one({"key": key})
214+
if document:
215+
# Check if 'code' exists and is not empty
216+
code = document.get("code")
217+
if code:
218+
try:
219+
result = await execute_async_code(code)
220+
return RedirectResponse(url=result)
221+
except Exception as e:
222+
# Extract the traceback from the exception
223+
tb_str = ''.join(traceback.format_exception(None, e, e.__traceback__))
224+
# Pass the traceback to the template
225+
return templates.TemplateResponse("error_page.html", {
226+
"request": request,
227+
"error_message": "An error occurred while processing your code.",
228+
"traceback": tb_str,
229+
"messages": [["danger", "An error occurred while executing your code."]]
230+
})
231+
else:
232+
return "The 'code' field is empty.", 400 # Bad request error for empty 'code'
233+
return "Handler function not found.", 404 # Not found error if document doesn't exist.
234+
235+
@app.head("/redirect/{key}", response_class=HTMLResponse)
210236
async def dynamic_redirect(request: Request, key: str):
211237
"""Dynamically handle redirects based on MongoDB data."""
212238
collection = db.route_handlers

0 commit comments

Comments
 (0)