FastAPI系列:HttpBasic基本认证
HttpBasic基本认证
from fastapi import FastAPI, Depends
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.exceptions import HTTPException
from fastapi.responses import PlainTextResponse
from starlette.status import HTTP_401_UNAUTHORIZED
app = FastAPI(
title='HttpBasic基本认证示例',
description='HttpBasic基本认证示例',
version='v1.1.0'
)
security = HTTPBasic()
@app.get('/login')
async def login(credentials: HTTPBasicCredentials = Depends(security)):
# HTTPBasicCredentials对象可以获取到用户名和密码
if credentials.username != 'jack' or credentials.password != '123456':
raise HTTPException(status_code=HTTP_401_UNAUTHORIZED, detail='用户名或密码错误',headers={'WWW-Authenticate': 'Basic'})
else:
return PlainTextResponse('登录成功')
if __name__ == '__main__':
import uvicorn
uvicorn.run('main:app', host='0.0.0.0', port=8000, reload=True)
-------------------------------------------
个性签名:代码过万,键盘敲烂!!!
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!