我想启用 API 密钥标头以使用 FastAPI 在我的 API 中生成不记名令牌,但我在从 OpenAPI UI 获取和发送不记名令牌时遇到问题,我的令牌端点如下所示
api_key_header = APIKeyHeader(name='X-API-Key', auto_error=True)
app_auth = APIRouter()
@app_auth.post('/token', summary="Returns Bearer Token",
tags=["Auth"])
async def login(api_key_header: str = Security(api_key_header)):
if api_key_header != '123':
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED,
detail='wrong api key',
headers={"WWW-Authenticate": "Bearer"})
else:
jwt_token = create_jwt_token(user)
return jwt_token
Run Code Online (Sandbox Code Playgroud)
但是,我通过 OpenAPI 将生成的令牌传递到另一个端点时遇到了麻烦(如果我只是将它发送到其他客户端的标头中,它就可以工作),当我测试其他端点时,它不会在标头中发送令牌

我也启用了
oauth_schema = OAuth2PasswordBearer(tokenUrl='/token')
Run Code Online (Sandbox Code Playgroud)
app = FastAPI(title="My test api", version="1.0")
app.include_router(app_auth)
app.include_router(app_test, prefix='/v1.0', dependencies=[Depends(check_jwt_token)])
Run Code Online (Sandbox Code Playgroud)
和 check_jwt_token
async def check_jwt_token(token: str = Depends(oauth_schema)):
"""
it decods the token and check if …Run Code Online (Sandbox Code Playgroud) 我有一个像这样的熊猫数据框:
df = pd.DataFrame({"Id": [1, 1, 1, 2, 2, 2, 2], "字母": ['A', 'B', 'C', 'A', 'D '、'B'、'C']})
如何有效地添加新列“合并”,以便将“letter”列中的所有值通过“Id”连接起来,因此最终的数据框将如下所示:
我正在学习使用 FastAPI,并且在实现一个简单的 API 时一遍又一遍地出现此错误,但我无法弄清楚原因
"detail": "There was an error parsing the body"
Run Code Online (Sandbox Code Playgroud)
这发生在我这两个端点上:
完整代码:代码库
片段:
app_v1 = FastAPI(root_path='/v1')
# JWT Token request
@app_v1.post('/token')
async def login_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
jwt_user_dict = {"username": form_data.username, "password": form_data.password}
jwt_user = JWTUser(**jwt_user_dict)
user = authenticate_user(jwt_user)
if user is None:
return HTTP_401_UNAUTHORIZED
jwt_token = create_jwt_token(user)
return {"token": jwt_token}
Run Code Online (Sandbox Code Playgroud)
要求:
@app_v1.post("/user/photo")
async def update_photo(response: Response, profile_photo: bytes = File(...)):
response.headers['x-file-size'] = str(len(profile_photo))
response.set_cookie(key='cookie-api', value="test")
return {"profile photo size": len(profile_photo)}
Run Code Online (Sandbox Code Playgroud)
我正在运行一些测试,其中一个将异常与其消息进行比较,看起来像这样,BaseCallback只是一个具有来自 的抽象方法的类abc,我正在测试如果未故意使用继承定义方法,则会出现错误我错过了__call__基类强制的方法
from base import BaseCallback
import pytest
def test_base_callback_call():
class MyDummyCallback(BaseCallback):
def __init__(self, metric):
self.metric = metric
def on_step(self, record=None, logbook=None, estimator=None):
print(record)
with pytest.raises(Exception) as excinfo:
callback = MyDummyCallback(metric="fitness")
assert (
str(excinfo.value) == "Can't instantiate abstract class MyDummyCallback with abstract methods __call__ "
)
Run Code Online (Sandbox Code Playgroud)
问题是我正在同时测试多个Python版本,它适用于Python 3.6、3.7和3.8,但在Python 3.9中,断言消息从“无法使用抽象方法调用实例化抽象类MyDummyCallback”更改为“ Can ” '不使用抽象方法 调用实例化抽象类 MyDummyCallback ”
所以这使得我的测试失败,因为缺少S
有没有办法在此函数中设置有效的 python 版本(例如从 3.6 到 3.8)并为 python 3.9 创建另一个测试?或者处理这种变化的建议方法是什么?
我通过检查 2 条消息中的 1 条进行了扭转,如果至少存在 …