[英]Python/FastAPI: how can I get headers or a specific header from my backend API?
I want to retrieve a specific header from my API inside a function with fastAPI, but I can't found a solution for this.我想从带有 fastAPI 的函数内的 API 中检索特定标头,但我找不到解决方案。
In flask was simply: request.headers['your-header-name']
在烧瓶中很简单:
request.headers['your-header-name']
Why the hell with fastAPI is so complicated to do a simple thing like this?为什么 fastAPI 这么复杂,做这样一个简单的事情?
Anyone know a solution to retrieve a header?有人知道检索标题的解决方案吗? Thanks :)
谢谢 :)
The decorator:装饰师:
def token_required(f):
@wraps(f)
def decorator(*args, **kwargs):
CONFIG = settings.read_config()
token = None
headers = Request.headers
if "Authorization" in headers:
auth_header = Request.headers
token = auth_header
elif not token:
return {"Error": "Token is missing or incorrect header name"}, 401
try:
public_key = CONFIG["APPLICATION"]["PUBLIC_KEY"]
claim = jwt.decode(token, public_key)
claim.validate()
except UnicodeDecodeError as err:
return {"Error": f"An error occurred -> {err} check your token"}, 401
return f(*args, **kwargs)
return decorator
I need to read 'Authorization' header to check if exist or not.我需要阅读“授权”标头以检查是否存在。
It's pretty similar, you can do它非常相似,你可以做
from fastapi import FastAPI, Request
@app.get("/")
async def root(request: Request):
my_header = request.headers.get('header-name')
...
NOTE: that it's lowercased注意:它是小写的
Example:例子:
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/")
async def root(request: Request):
my_header = request.headers.get('my-header')
return {"message": my_header}
Now if you run this app with uvicorn on your localhost, you can try out sending a curl
现在,如果您在本地主机上使用 uvicorn 运行此应用程序,则可以尝试发送
curl
curl -H "My-Header: test" -X GET http://localhost:8000
This will result in这将导致
{"message":"test"}
UPD:更新:
if you need to access it in decorator you can use following如果您需要在装饰器中访问它,您可以使用以下
def token_required(func):
@wraps(func)
async def wrapper(*args, request: Request, **kwargs):
my_header = request.headers.get('my-header')
# my_header will be now available in decorator
return await func(*args, request, **kwargs)
return wrapper
Or, as described in the fastapi documentation ( https://fastapi.tiangolo.com/tutorial/header-params/ ):或者,如 fastapi 文档( https://fastapi.tiangolo.com/tutorial/header-params/ )中所述:
from typing import Optional
from fastapi import FastAPI, Header
app = FastAPI()
@app.get("/items/")
async def read_items(user_agent: Optional[str] = Header(None)):
return {"User-Agent": user_agent}
this will fetch the user_agent
header parameter.这将获取
user_agent
标头参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.