FastAPI框架

FastAPI框架

该框架的速度(天然支持异步)比一般的django和flask要快N多倍

使用该框架需要保证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=8085)

模版渲染

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

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

安装

pip3 install jinja2

使用

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


app = FastAPI()
# 挂载模板文件夹 directory后面是真正的文件夹名字
temp = Jinja2Templates(directory='templates')

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

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

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

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)

files.html

FastAPI框架
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    

</head>
<body>
<h1>单个文件</h1>
<form action="/file/" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="file" name="file_obj">
    <input type="text" name="info">
    <input type="submit">
</form>

<h1>多个文件</h1>
<form action="/files/" method="post" enctype="multipart/form-data">
    <input type="file" name="files_list" multiple>
<!--{#    multiple加上就支持一次性传多个文件#}-->
    <input type="file" name="files_obj_list" multiple>
    <input type="submit">
</form>
</body>
</html>
View Code

index.html

FastAPI框架
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<h1>单个文件</h1>
<h1>{{ file_size }}</h1>
<h1>{{ file_name }}</h1>
<h1>{{ info }}</h1>
<h1>{{ file_content_type }}</h1>


<h1>多个文件</h1>
<h1>{{ file_sizes }}</h1>
<h1>{{ file_names }}</h1>
</body>
</html>
View Code

静态文件配置

from starlette.staticfiles import StaticFiles
# 挂载静态文件夹 '/static'是前端引用的名字,name是起别名
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>

 

 

上一篇:FastAPI开源项目改造之添加虚拟环境


下一篇:(完结篇)Python框架FastAPI:比Flask和Tornada更高性能的API 框架