Python FastApi框架基础教学

下载配置文件:

aiofiles==0.6.0
atomicwrites==1.4.0
attrs==20.3.0
bcrypt==3.2.0
certifi==2020.12.5
cffi==1.14.4
chardet==4.0.0
click==7.1.2
colorama==0.4.4
cryptography==3.3.1
dnspython==2.0.0
ecdsa==0.14.1
email-validator==1.1.2
fastapi==0.63.0
h11==0.11.0
idna==2.10
importlib-metadata==3.3.0
iniconfig==1.1.1
Jinja2==2.11.2
MarkupSafe==1.1.1
packaging==20.8
passlib==1.7.4
pluggy==0.13.1
py==1.10.0
pyasn1==0.4.8
pycparser==2.20
pydantic==1.7.3
pyparsing==2.4.7
pytest==6.2.1
python-jose==3.2.0
python-multipart==0.0.5
requests==2.25.1
rsa==4.6
six==1.15.0
SQLAlchemy==1.3.22
starlette==0.13.6
toml==0.10.2
typing-extensions==3.7.4.3
urllib3==1.26.2
uvicorn==0.13.2
zipp==3.4.0

01.开启服务和连接接口

file1.py


from  fastapi import FastAPI
app = FastAPI()


#支持一种请求方式
@app.post("/")
def login():
    return {"msg":"登录接口"}




#支持多种请求方式
@app.api_route("/login",methods=['POST',"PUT","DELETE",'GET'])
def login2():
    return "aaaa"



#启动命令
    uvicorn py文件名称:实例化FastApi对象名称 --reload

    uvicorn file1:app --reload

02.传参方式

        第一种:路由传参

from  fastapi import FastAPI
app1 = FastAPI()


#路由传参
@app.get("/index/{id}")
def index(id):
    return {"id":id}





测试路由传参

Python FastApi框架基础教学_第1张图片

 

        第二种query传参

        

from  fastapi import FastAPI
app = FastAPI()


@app.get('/index')
def index(id):
    return [id]

        测试query传参数

Python FastApi框架基础教学_第2张图片

#接受请求头传参

from  fastapi import FastAPI,Header
app = FastAPI()

@app.get('/index')
#默认token为None
def index(token=Header(None)):
        return {"token":token}


 测试请求头传参

Python FastApi框架基础教学_第3张图片

 #传送JSON数据POST请求

from  fastapi import FastAPI,Header,Body
app = FastAPI()

@app.post('/index')
def index(data=Body(None)):
    return {"data":data}



测试JSON传参

Python FastApi框架基础教学_第4张图片

#form表单传参

from  fastapi import FastAPI,Header,Body,Form
app = FastAPI()

@app.post('/index')
def index(username=Form(None),pwd=Form(None)):
    return {"username":username,"pwd":pwd}



测试form表单传参

 Python FastApi框架基础教学_第5张图片

#修改响应头和状态码

from fastapi import FastAPI
from fastapi.responses import JSONResponse


app = FastAPI()


@app.get("/")
def index():
    return JSONResponse(content={"msg":"哈哈哈"}
                        ,status_code=202,
                        headers={"a":"b"}
                        )

 测试修改响应头和状态码

#渲染图片,但是,你去请求接口时,他不会直接渲染,而是下载

from fastapi import FastAPI
from fastapi.responses import JSONResponse,HTMLResponse,FileResponse
from fastapi.templating import Jinja2Templates

app = FastAPI()


@app.get("/")
def index():
    img = "static\向日葵.jpg"
    return FileResponse(img,filename="向日葵.jpg")

#渲染HTML模板

你可能感兴趣的:(fastapi)