当前位置:网站首页>Fastapi learning Day1
Fastapi learning Day1
2022-06-30 06:37:00 【IQ catch urgent ("") consult the great God】
Catalog
send out post request , use postman test
Request header pass parameters Header
Request body passing parameters
json Format transfer data ,Body class
form Transfer data in form format , Import Form class
JSONResponse The format of the returned data is json object
HTMLResponse The way to return data is html page
FileResponse The way to return data is by file
Return through the template engine HTML page
install pyCharm
Download Community Edition , Just refer to other bloggers , Note that file——settings——project——project interpreter Package management
Using skills
file——Settings——Appearance Set the background color and the font and font size of the toolbar

file——Settings——Editor——font Set the font size and line spacing of the editing page

file——Settings——Editor——File Encodings Set the encoding form

FastAPI yes python web frame , The focus is on asynchronous programming ,python3.6 Above version
It can be used FastAPI Develop web site 、 Development web API、 Make a test platform 、 Continuous integration tools 、 Generating documentation
Create project
choice new environment using Will create a venv Virtual environment for , The advantage of this is that each project is an independent space , There will be no version dependency conflicts , It will not pollute the previous system environment

choice previously configured interpreter, The previously configured interpreter , Then select the... On your computer python edition , Then the virtual environment will be created , stay file——settings——project——project interpreter in
show all—— + —— New environment A virtual environment venv —— ok

The results of the two methods are the same , Definitely choose the first
install FastAPI Tools for
Method 1 : stay pyCharm Package management tools can be used in
stay file——settings——project——project interpreter in , Click on +, Search for fastapi, Click on Install

Method 2 : Common methods , Applicable to all editors
Open the terminal (pyCharm: Terminal)
Get into venv A virtual environment ——venv\Scripts\activate.bat, Then install fastapi
pip install fastapi[all]
To save memory space , What libraries can be used and what libraries are being installed , Do not install all
pip install fastapi——pip install uvicorn,uvicorn Is the server , The most basic thing is to need these two
pip list View installed Libraries
Use FastAPI
1. Import from fastapi import FastAPI
2. Initialize object app=FastAPI()
3.main function
Method 1 :
if __name__ == '__main__':
uvicorn.run(app)
Method 2 : At terminal uvicorn main:app --reload (main File name )
notes
1. fastapi Document path
2. """ The annotation information will be synchronized to the document """
send out post request , use postman test
@app.post("/login")
def login():
return {"msg":"login success"}# Support multiple requests
@app.api_route("/login",methods=("GET","POST"))
def login():
return {"msg":"login success"}obtain URL Parameters
# /city/{city}?q=xx city Is the path parameter ,?q=xx For query parameters , It is required after operation , Otherwise, it will report a mistake , add option after Query parameters become optional
#http://127.0.0.1:8000/city/Beijing?query_string=xx
@app.get('/city/{city}')
def city(city:str, query_string: Optional[str]=None):
return {'city':city, 'query_string': query_string}# test http://127.0.0.1:8000/user/2 , 2 For the parameters passed
@app.get("/user/{id}") / Additive variables
def user(id):
return {"id":id}# http://127.0.0.1:8000/stu?id=8 Query string
@app.get("/stu") ? Additive variables
def stu(id):
return {"id":id}
Different method paths can be the same
@app.post('/stu')
def stu():
return {"hello":"world"}Request header pass parameters Header
Get the user name and password token, Is stored in the request header , You need to import Header, use token Value to access other interfaces , That is, use the request header to pass parameters
@app.get("/pra")
def pra(id,token=Header(None)): # Default parameters , The names have to be consistent ,token——postman Inside, too token
return {"id":id,"token":token}
Request body passing parameters
# Request body Body, Default parameters , Random names
@app.post("/login")
def login(a=Body(None)):
return {"a":a}json Format transfer data ,Body class

form Transfer data in form format , Import Form class
Ensure that the accepted field name is consistent with the passed field name ,Form The form class needs to be downloaded python-multipart
@app.post("/login")
def login(name=Form(None),age=Form(None)):
return {"data":{"name":name,"age":age}}
Modify response status code
JSONResponse The format of the returned data is json object
Import required from fastapi.responses import JSONResponse
# content Returned data status_code Status code headers You can add parameters in the request header
@app.get("/user")
def user():
return JSONResponse(content={"msg":"get user"},
status_code=202,
headers={"a":"b"})
HTMLResponse The way to return data is html page
@app.get("/")
def user():
html_content = """"
<html>
<body><p style="color:red">Hello World</p></body>
</html>
"""
return HTMLResponse(content=html_content)
FileResponse The way to return data is by file
@app.get("/avatar")
def user():
avatar = 'static/mage.jpg'
return FileResponse(avatar,filename="mage.jpg")No, filename="mage.jpg" Parameters , The browser directly displays the picture , You have this parameter , The browser will prompt to download the picture
Need to download a package :aiofiles—— pip install aiofiles

Return through the template engine HTML page
from fastapi.templating import Jinja2Templates Common template engine
install pip install jinja2
The data of pages on the web will change , All you need Request obtain
from fastapi import FastAPI,Request
from fastapi.templating import Jinja2Templates
app = FastAPI()
template = Jinja2Templates("pages")
# Return through the template engine HTML page , context Parameters cannot be left blank , And inside must be request
@app.get("/")
def user(username,req: Request):
return template.TemplateResponse("index.html",context={"request":req,"name":username})username Put the obtained data into the template engine
"name":username—— username It's from the background ,name It's the front end , Background rendering to foreground

边栏推荐
- ES6 array traversal and Es5 array traversal
- Redux source code implementation
- [wechat applet: single or multiple styles, background color, rounded corners]
- 一个完整的性能测试流程
- 阿里云买的40G高效云盘挂载只有20G
- 反编译正常回编译出现问题自己解决办法
- Application of redis client list in practice
- INI analyse les documents d'apprentissage
- Wuenda coursera deep learning course
- 神经网络入门
猜你喜欢
随机推荐
Arrangement of in-depth learning materials
The 40g high-efficiency cloud disk purchased by Alibaba cloud is only 20g attached
Using C language pure for loop to implement ilovey
Ten years' miscellaneous thoughts
To: k210 realizes face recognition (code interpretation attached)
Thread safe solutions, communication between threads (classic examples of producers and consumers)
Rhcsa day 3
力扣------替换空格
Go pack and unpack
File operation io-part1
How does Altium designer hide some temporarily unnecessary classes, such as GND
Base64 explanation: playing with pictures Base64 encoding
INI analyse les documents d'apprentissage
[untitled]
1.7 - CPU performance indicators
Bat usage details 2
Is Huatai stock trading safe? I want to open an account online.
Installation and initialization of MariaDB database
Use of observer mode and status mode in actual work
Static routing job









