微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 FASTAPI 处理查询?

如何解决如何使用 FASTAPI 处理查询?

我有 web 服务器和 index.html 页面,当用户在本地主机中键入:8000 到浏览器时,将显示这些页面。我目前正在使用 fastapi 和 python。 index.html 包含两个文本框和一个提交按钮。它允许用户在文本框中输入数据,提交按钮将生成查询。例如“GET /?query1=1&query2=2”。我该如何处理查询?创建另一个端点?

app = FastAPI() 
templates = Jinja2Templates(directory= “templates”)
@app.get(“/“)
def root(request:Request):
return templates.TemplateResponse(“index.HTML,{request:request})

解决方法

您可以像这样获取查询参数:

@app.get("/")
def root(query1: int,query2: int):
    query1 = query1
    query2 = query2
    return templates.TemplateResponse(...)

或者像这样:

@app.get("/")
async def root(request:Request):
    query1 = request.query_params["query1"]
    query2 = request.query_params["query2"]
    return templates.TemplateResponse(...)

您可以阅读有关查询参数 here 的信息。

FastApi Request 在幕后使用 Starlette。您可以阅读关于 Startlette Request here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。