简体   繁体   English

Python/FastAPI:如何从后端 API 获取标头或特定标头?

[英]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.

相关问题 如何从我的 FastAPI 应用程序向另一个站点 (API) 发送 HTTP 请求? - How can I send an HTTP request from my FastAPI app to another site (API)? 如何在前端使用 Fetch API 下载从 FastAPI 后端返回的文件? - How do I download a file returned from FastAPI backend using Fetch API at the frontend? Python 启用 FastAPI API 密钥 header - Python enable FastAPI API Key header "如何使用 Python 从网络选项卡的特定请求的“请求标头”中获取信息?" - How can I fetch info from the "Request Headers" of a specific request from the network tab using Python? 如何在 python 中不断从屏幕的特定部分获取单词 - How can I constantly get a word from a specific part of my screen in python 在使用python向Stackoverflow API发出请求时,如何通过标头传递API密钥 - How can I pass my API key through header while making request to Stackoverflow API using python 如何在调用更新后端 state 的 function 时从 python (fastapi) 发送服务器端事件 - How to send server-side events from python (fastapi) upon calls to a function that updates the backend state 如何从特定用户 django python 获取数据 - How can I get data from specific user django python 我如何从 python 字典中获取特定的元素和键 - How can i get specific Element and key from python Dictionary 我怎样才能获取到 fastapi - how can i fetch to fastapi
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM