我正在使用 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)
我该如何解决这个问题?先谢谢您的帮助。
我想使用从 发送数据app.post()到。app.get()RedirectResponse
@app.get('/', response_class=HTMLResponse, name='homepage')
async def get_main_data(request: Request,
msg: Optional[str] = None,
result: Optional[str] = None):
if msg:
response = templates.TemplateResponse('home.html', {'request': request, 'msg': msg})
elif result:
response = templates.TemplateResponse('home.html', {'request': request, 'result': result})
else:
response = templates.TemplateResponse('home.html', {'request': request})
return response
Run Code Online (Sandbox Code Playgroud)
@app.post('/', response_model=FormData, name='homepage_post')
async def post_main_data(request: Request,
file: FormData = Depends(FormData.as_form)):
if condition:
......
......
return RedirectResponse(request.url_for('homepage', **{'result': str(trans)}), status_code=status.HTTP_302_FOUND)
return RedirectResponse(request.url_for('homepage', **{'msg': str(err)}), status_code=status.HTTP_302_FOUND)
Run Code Online (Sandbox Code Playgroud)
result或msg通过RedirectResponse,url_for() …我有一个包含学生表格的页面。我添加了一个按钮,允许您向表中添加新行。为此,我将用户重定向到带有输入表单的页面。
问题是,提交完成的表单后,用户会转到一个新的空白页面。如何传输已完成表单中的数据并将用户重定向回表格?
我刚刚开始学习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) 我创建了一个登录路径,在其中发布表单数据并设置 cookie。设置 cookie 后,我重定向到“/main”,在那里我得到{detail:"Method Not Allowed"}响应。
@app.post("/login")
async def login(request:Request):
response = RedirectResponse(url="/main")
response.set_cookie(key="cookie",value="key-value")
return response
@app.get("/main")
async def root(request:Request, cookie: Optional[str] = Cookie(None)):
if cookie:
answer = "set to %s" % cookie
else:
answer = "not set"
return {"value": answer}
Run Code Online (Sandbox Code Playgroud)
我进一步检查了控制台,发现在重定向期间向“/main”发出了 POST 请求,从而导致了错误。当我将其更改为app.post("/main")它时,效果很好。我该如何避免这个错误?我不想每次都发出访问“/main”的发布请求。提前致谢。