fastapi 学习记录

本文是关于FastAPI的学习记录,涵盖了从创建应用、处理静态文件、参数处理(包括路径、查询字符串、表单、请求体和依赖)、响应、中间件、CORS、异常处理、BackgroundTasks、类视图、JWT认证、WebSocket以及使用uvicorn和supervisor进行部署的详细内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

安装模块

pip install fastapi

1.创建app

from fastapi import FastAPI

app = FastAPI()

@app.get()
async def index():
    return ok

2.静态文件路径

from fastapi.staticfiles import StaticFiles

static = StaticFiles(directory='./statics') # 静态文件目录名称可以直接写‘statics’

app.mount('/static',static,name='')    # 第一个参数是访问静态文件的uri,name的作用是方便反向解析

3.模板(前后端不分离)

from fastapi.templating import Jinja2Templates

template=Jinja2Templates(directory='./templates')    # 存放模板的目录

# JinJa2模板引擎  渲染时调用
template.TemplateResponse('模板文件.html',context={
   'request':request,***})
# 当后端渲染时,必须返回前端request对象,以及其他参数,可以是python对象
# 在html页面模板中,可以使用 {
   { python对象 }} 渲染,例如  context={'request':request,'name':'test'}

# 想要渲染出name的值,只需要  {
   { name }},即可在浏览器中显示name对应的值’test‘
# JinJa2模板引擎还提供了for循环、if判断等方法

# example   context={'request':request,'a':[1,2,3,4]}
{
   % for i in a %}
	<li>{
   {
    i }}</li>
{
   % endfor %}


{
   % for i in a %}
	{
   % if i<2 %}
	<li>{
   {
    i }}</li>
    {
   % else %}
    <li>{
   {
    i+1 }}</li>
    {
   % endif %}
{
   % endfor %}

4.参数

4.1路径参数
from fastapi import FastAPI,Path

app = FastAPI()

@app.get('/{id}')
async def func1(id:int):    # id就是路径参数,设置了类型校验
    pass

@app.get('/test/{id}')
async def func2(id:int=Path(...,ge=1)):    # Path是路径参数的类,可以做验证,即对路径参数的校验
    pass

Path(  # noqa: N802
    default: Any,                          # None为非必传参数,...为必传,指定值为默认
    *,									   # 如果传了*,则说明后面的参数全部为关键字参数
    alias: str = None,					   # 别名,至前端传参时的参数名
    title: str = None,					   # 说明
    description: str = None,
    gt: float = None,					   # 只对int/float格式的参数,gt:大于
    ge: float = None,					   # ge :大于等于
    lt: float = None,                      # lt :小于
    le: float = None,					   # le:小于等于
    min_length: int = None,				   # 只能用于str格式的参数,最小长度
    max_length: int = None,				   # 只能用于str格式的参数,最大长度
    regex: str = None,					   # 只能用于str格式的参数,正则
    deprecated: bool = None,
    **extra: Any,
)
4.2查询字符串参数
from fastapi import FastAPI,Query

app = FastAPI()

@app.get('/')
async def func1(a:str,b:int):    # 直接定义要接收的参数,只能校验类型
    pass

@app.get('/1')
async def func2(a:str=Query(),b:int=Query()):    # 可以校验类型以及其他的参数,与Path类似
    pass

4.3表单参数
from fastapi import Form,UploadFile
from typing import List
app = FastAPI()


@app.post('/index/dc')
async def index_post(request: Request, file1: bytes = File(...), name: str = Form(None), age: int = Form(None)):
    print(name)
    return name, age

# 或者使用UploadFile进行校验
@app.post('/index/dc')
async def index_post(request: Request, file1: UploadFile = File(...), name: str = Form(None), age: int = Form(None)):
    print(name)
    return name, age

想要使用表单,必须先安装python-multipart 模块

<form action="./index/dc" method="post" enctype="multipart/form-data">
    <input type="file" name="file1">
    <input type="text" name="name">
    <input type="text" name="age">
    <input type="submit" >
</form
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值