首页 > 其他分享 >FastAPI系列:HttpBasic基本认证

FastAPI系列:HttpBasic基本认证

时间:2024-02-28 19:25:27浏览次数:24  
标签:__ FastAPI 认证 fastapi import 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)

标签:__,FastAPI,认证,fastapi,import,HttpBasic
From: https://www.cnblogs.com/weiweivip666/p/18041488

相关文章

  • FastAPI系列:jwt认证
    jwt认证1.头部Header,主要是对jwt元数据的描述{'alg':'HS256','typ':'JWT'}2.载荷playload,主要包含jwt信息需要传递的主体数据{'iss':'jack',#由jwt签发'sub':'jack',#该jwt面向的用户组,也称为主题......
  • FastAPI系列:异步redis
    aioredisofficialwebsiteInstallpipinstallaioredisConnecttoredisfromfastapiimportFastAPIimportaioredisapp=FastAPI()@app.on_event('startup')asyncdefstartup_event():#创建的是线程池对象,默认返回的结果为bytes类型,设置decode_responses表......
  • FastAPI系列:fastapi定制的数据库操作库sqlmodel
    官网sqlmodel安装#安装sqlmodel会自动安装pydantic和sqlalchemypipinstallsqlmodel使用#步骤1,创建sqlmodel引擎fromsqlmodelimportcreate_engine#driver://用户名:密码@ip/数据库engine=create_engine("mysql+mysqldb://root:123456@localhost/api")#步骤......
  • FastAPI系列:自定义认证
    fromtypingimportOptional,TuplefromfastapiimportFastAPI,RequestfrompydanticimportBaseModel#通过starlette.authentication导入AuthenticationBackendfromstarlette.authenticationimportAuthenticationBackend,AuthenticationError,AuthCredentials,S......
  • FastAPI系列:依赖注入
    函数式依赖项fromfastapiimportFastAPIfromfastapiimportQuery,Dependsfromfastapi.exceptionsimportHTTPExceptionapp=FastAPI()defusername_check(username:str=Query(...)):ifusername!='zhong':raiseHTTPException(status_code......
  • FastAPI系列:环境配置读取
    依赖包pipinstallpython-dotenv使用#.env文件ADMIN_EMAIL="[email protected]"APP_NAME="ChimichangApp"#config.pyfrompydantic_settingsimportBaseSettingsclassSettings(BaseSettings):app_name:str="AwesomeAPI"......
  • FastAPI系列:后台任务进程
    注:后台任务应附加到响应中,并且仅在发送响应后运行用于将单个后台任务添加到响应中fromfastapiimportFastAPIfromfastapi.responsesimportJSONResponsefromstarlette.backgroundimportBackgroundTaskfrompydanticimportBaseModelapp=FastAPI()classUser(B......
  • FastAPI系列:中间件
    中间件介绍中间件是一个函数,它在每个请求被特定的路径操作处理之前,以及在每个响应返回之前工作装饰器版中间件1.必须使用装饰器@app.middleware("http"),且middleware_type必须为http2.中间件参数:request,call_next,且call_next它将接收request作为参数@app.middleware("h......
  • FastAPI系列:模型用法
    模型基本用法frompydanticimportBaseModelclassItem(BaseModel):#通过继承BaseModelname:strprice:floatis_offer:Union[bool,None]=None常用的模型属性和方法dict()#将数据模型的字段和值封装成字典json()#将数据模型的字段和值封装成json格......
  • FastAPI系列:上传文件File和UploadFile
    上传文件#file仅适用于小文件@app.post("/files/")asyncdefcreate_file(file:bytes|None=File(default=None)):ifnotfile:return{"message":"Nofilesent"}else:return{"file_size":len(file)}......