Use FastAPI to develop python3 interface

FastAPI documentation  https://fastapi.tiangolo.com/

FastApi is an asynchronous web framework, its speed is very very very fast. Far more than Flask. The speed can match the interface written in Golang

There is an official docker image for easy deployment with docker

 

1. Install FastAPI module

python3 -m pip install fastapi

 

2. Install Uvicorn module (ASGI server used in production environment)

Uvicorn is a lightning-fast ASGI server built on uvloop and httptools

python3 -m pip install uvicorn

 

3. Create main.py file

#!encoding=utf8
  
from fastapi import FastAPI

app = FastAPI()


@app.get("/")
def read_root():
    return {"Hello": "World"}

4. Start ASGI Server

uvicorn main:app --reload

该命令uvicorn main:app指的是:

main:文件main.py(Python“模块”)。
app:main.py在线内创建的对象app = FastAPI()。
--reload:更改代码后使服务器重新启动。这样做是为了开发

After executing the command, there will be the following output

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [13201]
INFO:     email-validator not installed, email fields will be treated as str.
To install, run: pip install email-validator
INFO:     Started server process [13203]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Explains the server address and port number for accessing http, as well as the exit method

 

5. Browser visit   http://127.0.0.1:8000

Will be displayed in the browser 

{"Hello":"World"}

Description interface access is successful

 

6. View the interface documents, there are two interface documents

http://127.0.0.1:8000/docs

http://127.0.0.1:8000/redoc

 

The above are the contents of the official documentation. For detailed usage, please visit the official documentation directly.

Guess you like

Origin blog.csdn.net/wuchenlhy/article/details/104053134