0

I created a tool in flask, but want to move it to fastapi. I defined two routes as follows:

from fastapi import FastAPI, Request, Form
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse


@app.get("/mytool")
async def home(request: Request, response_class=HTMLResponse):
    # displays tool 
    return templates.TemplateResponse("index_tool.html", {"request": request})


@app.post("/mytool")
async def home(request: Request, 
               var1: str = Form(), 
               var2: str = Form(), 
               var3: int = Form(), 
               var4: int = Form()):

    # ... perform calculation 
    result = myCalculation(var1, var2, var3, var4)
    return templates.TemplateResponse("index_tool.html", {"request": request, 
                                                          "result": result})

However, whenever I submit the form. It gives the error POST / HTTP/1.1" 405 Method Not Allowed, even though I defined both the GET and POST route. How should I go about creating such a tool?

0

1 Answer 1

2

There's a few issues. You're using the same method name (home) for both the post and the get endpoint - this will make it hard to use url_for in your templates to get the actual endpoint from a route name.

Your POST in the log is against /, not against /mytool which is the path you've registered in your code.

POST / HTTP/1.1" 405 Method Not Allowed
     ^

vs

@app.post("/mytool")
           ^^^^^^^

Since you haven't included your actual template where the form element defines where the submission should be sent, you should probably replace it with something like:

<form method="post">

.. if the URL is the same, or if you fix the function names, you can do:

<form method="post" action="{{ url_for('home_calculate') }}">
Sign up to request clarification or add additional context in comments.

1 Comment

silly me, it was caused by the same method name. Too busy looking for problems elsewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.