基于我之前的问题,我现在需要在响应中添加一个标头。
根据文档,我可以简单地将标题和另一个属性添加到RedirectResponse对象中。
当我对此进行测试时,它似乎没有携带标头值。
根据这篇文章,不可能为重定向请求设置标头。所以,而不是重定向,也许我应该尝试其他方法?
有任何想法吗?
from fastapi import FastAPI, Request
from starlette.responses import RedirectResponse
app = FastAPI()
@app.get("/data/")
async def api_data(request: Request):
params = str(request.query_params)
url = f'http://some.other.api/{params}'
headers = {'Authorization': "some_long_key"}
response = RedirectResponse(url=url, headers=headers)
return response
Run Code Online (Sandbox Code Playgroud) 我有一个基于 FastAPI 的应用程序,它作为网站的后端,当前部署在具有外部 IP 的服务器上。前端位于另一个开发人员处,暂时在本地托管。工作之初我们遇到了CORS问题,使用我在网上找到的如下代码解决了这个问题:
from fastapi.middleware.cors import CORSMiddleware
...
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:3000'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Run Code Online (Sandbox Code Playgroud)
添加内容允许 Frontend 正确发出请求,但由于某种原因,设置为发送(并在 Swagger UI 中正常工作)的 cookie 未在 Frontend 中设置。客户端看起来像:
axios({
method: 'POST',
baseURL: 'http://urlbase.com:8000',
url: '/login',
params: {
mail: 'zzz@zzz.com',
password: 'xxxxxx'
},
withCredentials: true
}).then( res => console.log(res.data) )
.catch( err => console.log(err))
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() …为什么 FastAPI 不将 cookie 返回到我的前端(这是一个 React 应用程序)?
这是我的代码:
@router.post("/login")
def user_login(response: Response,username :str = Form(),password :str = Form(),db: Session = Depends(get_db)):
user = db.query(models.User).filter(models.User.mobile_number==username).first()
if not user:
raise HTTPException(400, detail='wrong phone number or password')
if not verify_password(password, user.password):
raise HTTPException(400, detail='wrong phone number or password')
access_token = create_access_token(data={"sub": user.mobile_number})
response.set_cookie(key="fakesession", value="fake-cookie-session-value") #here I am set cookie
return {"status":"success"}
Run Code Online (Sandbox Code Playgroud)
当我从 Swagger UI autodocs 登录时,我可以使用 Chrome 浏览器上的 DevTools 在响应标头中看到 cookie。但是,当我从 React 应用程序登录时,没有返回 cookie。我正在使用 axios 发送这样的请求:
await axios.post(login_url, formdata)
我正在尝试在我的 FastAPI 应用程序中编写一个中间件,以便到达与特定格式匹配的端点的请求将被重新路由到不同的 URL,但我无法找到一种方法来做到这一点,因为它request.url是只读的。
我还在寻找一种在重新路由之前更新请求标头的方法。
这些事情在 FastAPI 中可能实现吗?
重定向是迄今为止我能做的最好的事情:
from fastapi import Request
from fastapi.responses import RedirectResponse
@app.middleware("http")
async def redirect_middleware(request: Request, call_next):
if matches_certain_format(request.url.path):
new_url = create_target_url(request.url.path)
return RedirectResponse(url=new_url)
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) 我正在开发一个 FastAPI 应用程序,该应用程序需要对用户访问的某些端点进行身份验证。我正在使用 FastAPI 中的 Oauth2 和 Jose 为我的身份验证过程创建 JWT。经过一些研究后,确保令牌在前端受到保护的最佳方法似乎是将它们存储在 HttpOnly Cookie 中。我正在努力了解如何通过 HttpOnly Cookie 正确传递 JWT,以便我的 FastAPI 服务器能够验证标头中的 JWT。目前,当我尝试将 JWT 令牌作为 HttpOnly Cookie 传递时,我得到一个401 Unauthorized Error.
当我将令牌作为模板字符串编码到标头中时,我已经能够使用 JWT 令牌成功地对用户进行身份验证。但是,当我通过标头将 JWT 作为 Cookie 传递到 FastAPI 服务器时,我的 FastAPI 服务器无法对用户进行身份验证并返回401 unauthorized error. 我尝试查看网络选项卡,看看我的请求中向 FastApi 服务器发送了哪些标头,以便更好地了解这两种情况之间的不同之处。
当我将 JWT 作为模板字符串传递并获得 200 响应时,这是在标头中:
身份验证:不记名令牌
async function getPosts() {
const url = "http://localhost:8000/posts";
const fetchConfig = {
headers: {
Authorization: `Bearer ${tokenValue}`,
},
};
const response = await fetch(url, …Run Code Online (Sandbox Code Playgroud)