返回 RedirectResponse 对象后,我遇到了奇怪的重定向行为
事件.py
router = APIRouter()
@router.post('/create', response_model=EventBase)
async def event_create(
request: Request,
user_id: str = Depends(get_current_user),
service: EventsService = Depends(),
form: EventForm = Depends(EventForm.as_form)
):
event = await service.post(
...
)
redirect_url = request.url_for('get_event', **{'pk': event['id']})
return RedirectResponse(redirect_url)
@router.get('/{pk}', response_model=EventSingle)
async def get_event(
request: Request,
pk: int,
service: EventsService = Depends()
):
....some logic....
return templates.TemplateResponse(
'event.html',
context=
{
...
}
)
Run Code Online (Sandbox Code Playgroud)
路由器.py
api_router = APIRouter()
...
api_router.include_router(events.router, prefix="/event")
Run Code Online (Sandbox Code Playgroud)
这段代码返回结果
127.0.0.1:37772 - "POST /event/22 HTTP/1.1" 405 Method Not …Run Code Online (Sandbox Code Playgroud) 我正在使用 FastAPIRedirectResponse并尝试将用户从一个应用程序(域)重定向到另一个应用程序(域),并在 ; 中设置一些responsecookie 然而,cookie 总是被删除/不被传输。如果我尝试添加一些标头,我添加到的所有标头RedirectResponse也不会传输。
@router.post("/callback")
async def sso_callback(request: Request):
jwt_token = generate_token(request)
redirect_response = RedirectResponse(url="http://192.168.10.1/app/callback",
status_code=303)
redirect_response.set_cookie(key="accessToken", value=jwt_token, httponly=True)
redirect_response.headers["Authorization"] = str(jwt_token)
return redirect_response
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?先谢谢您的帮助。
我想从 Jinja2 模板中调用 FastAPI 路由,并将路径和查询数据(参数)传递给该路由。我在 Jinja2 模板中尝试过如下所示:
{{ url_for('function1', uustr=data.uustr, interval=1) }}
Run Code Online (Sandbox Code Playgroud)
这是我想要调用的 FastAPI 路由(为了演示目的,语法已被简化):
@app.get("/updates/data/{uustr}",response_class=HTMLResponse)
async def function1(request: Request, uustr:str, interval:int):
return"""
<html>
<head>
<title>{{ uustr }}</title>
</head>
<body>
<h1>{{ interval }}</h1>
</body>
</html>
"""
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
raise ValueError('context must include a "request" key')
ValueError: context must include a "request" key
Run Code Online (Sandbox Code Playgroud)
有人有想法吗?
我有一个包含学生表格的页面。我添加了一个按钮,允许您向表中添加新行。为此,我将用户重定向到带有输入表单的页面。
问题是,提交完成的表单后,用户会转到一个新的空白页面。如何传输已完成表单中的数据并将用户重定向回表格?
我刚刚开始学习Web编程,所以我决定先不使用AJAX技术来实现。
代码:
from fastapi import FastAPI, Form
from fastapi.responses import Response
import json
from jinja2 import Template
app = FastAPI()
# The page with the table
@app.get('/')
def index():
students = get_students() # Get a list of students
with open('templates/students.html', 'r', encoding='utf-8') as file:
html = file.read()
template = Template(html) # Creating a template with a table
# Loading a template
return Response(template.render(students=students), media_type='text/html')
# Page with forms for adding a new entry
@app.get('/add_student')
def add_student_page():
with open('templates/add_student.html', …Run Code Online (Sandbox Code Playgroud)