FastAPI框架

目录

FastAPI框架

该框架的速度(天然支持异步)比一般的django和flask要快N多倍,号称可以比肩Go

使用该框架需要保证你的python解释器版本是3.6及以上

Ps:django3.X版本也支持异步,但是它的异步功能并没有真正的实现,还有很多bug

安装

pip3 install fastapi
pip3 install unicorn

基本使用

from fastapi import FastAPI


app = FastAPI()


@app.get(‘/‘)  # 点get就支持get请求
def read_root():
    return {"hello":‘world‘}


if __name__ == ‘__main__‘:
    import uvicorn
    uvicorn.run(app,host=‘127.0.0.1‘,port=8080)

模版渲染

fastapi本身是没有模版渲染功能的,需要你借助于第三方的模版工具

该框架默认情况下也是借助于jinja2来做模版渲染

安装jinja2

pip3 install jinja2

基本使用

from starlette.requests import Request
from fastapi import FastAPI
from starlette.templating import Jinja2Templates


app = FastAPI()
# 挂在模版文件夹
tmp = Jinja2Templates(directory=‘templates‘)


@app.get(‘/‘)
async def get_tmp(request:Request):  # async加了就支持异步
    return tmp.TemplateResponse(‘index.html‘,
                                {‘request‘:request,  # 一定要返回request
                                 ‘args‘:‘hello world‘  # 额外的参数可有可无
                                 }
                                )

@app.get(‘/{item_id}/‘)  # url后缀 
async def get_item(request:Request,item_id):
    return tmp.TemplateResponse(‘index.html‘,
                                {‘request‘:request,
                                 ‘kw‘:item_id
                                 })


if __name__ == ‘__main__‘:
    import uvicorn
    uvicorn.run(app,host=‘127.0.0.1‘,port=8080)

form表单数据交互

基本数据

from starlette.requests import Request
from fastapi import FastAPI,Form
from starlette.templating import Jinja2Templates


app = FastAPI()
tmp = Jinja2Templates(directory=‘templates‘)


@app.get(‘/‘)  # 接受get请求
async def get_user(request:Request):
    return tmp.TemplateResponse(‘form.html‘,{‘request‘:request})


@app.post(‘/user/‘)  # 接受post请求
async def get_user(request:Request,
                   username:str=Form(...),  # 直接去请求体里面获取username键对应的值并自动转化成字符串类型
                   pwd:int=Form(...)  # 直接去请求体里面获取pwd键对应的值并自动转化成整型
                   ):
    print(username,type(username))
    print(pwd,type(pwd))
    return tmp.TemplateResponse(‘form.html‘,{
        ‘request‘:request,
        ‘username‘:username,
        ‘pwd‘:pwd
    })


if __name__ == ‘__main__‘:
    import uvicorn
    uvicorn.run(app,host=‘127.0.0.1‘,port=8080)

文件交互

from starlette.requests import Request
from fastapi import FastAPI, Form, File, UploadFile
from starlette.templating import Jinja2Templates
from typing import List

app = FastAPI()
tmp = Jinja2Templates(directory=‘templates‘)


@app.get(‘/‘)  # 接受get请求
async def get_file(request: Request):
    return tmp.TemplateResponse(‘file.html‘, {‘request‘: request})


# 单个文件
@app.post(‘/file/‘)  # 接受post请求
async def get_user(request: Request,
                   file: bytes = File(...),
                   file_obj: UploadFile = File(...),
                   info: str = Form(...)
                   ):
    return tmp.TemplateResponse(‘index.html‘, {
        ‘request‘: request,
        ‘file_size‘: len(file),
        ‘file_name‘: file_obj.filename,
        ‘info‘:info,
        ‘file_content_type‘:file_obj.content_type
    })

# 多个文件
@app.post(‘/files/‘)
async def get_files(request:Request,
                    files_list:List[bytes] = File(...),  # [文件1的二进制数据,文件2的二进制数据]
                    files_obj_list:List[UploadFile]=File(...)  # [file_obj1,file_obj2,....]
                    ):
    return tmp.TemplateResponse(‘index.html‘,
                                {‘request‘:request,
                                 ‘file_sizes‘:[len(file) for file in files_list],
                                 ‘file_names‘:[file_obj.filename for file_obj in files_obj_list]
                                 }
                                )

if __name__ == ‘__main__‘:
    import uvicorn

    uvicorn.run(app, host=‘127.0.0.1‘, port=8080)

静态文件配置

from starlette.staticfiles import StaticFiles
# 挂载静态文件夹
app.mount(‘/static‘,StaticFiles(directory=‘static‘),name=‘static‘)


# 前端
<link rel="stylesheet" href="{{ url_for(‘static‘,path=‘/css/111.css‘) }}">
<script src="{{ url_for(‘static‘,path=‘/js/111.js‘) }}"></script>

相关推荐