Reputation: 880
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?
Upvotes: 0
Views: 2077
Reputation: 52882
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') }}">
Upvotes: 2