After using it for five minutes, I gave up the flash I had used for four years

There is a very simple requirement: write an HTTP interface, send a JSON string by POST, read the sent parameters in the interface, process one of the parameters, and return.

If we use Flask to develop this interface, the code is as follows:

from flask import Flask, request

app = Flask(__name__)


@app.route('/insert', methods=['POST'])
def insert():
    info = request.json
    name = info['name']
    age = info['age']
    age_after_10_years = age + 10
    msg = f'This person's name is:{name},10 Years later, this person's age:{age_after_10_years}'
    return {'success': True, 'msg': msg}
Copy code

The code looks very concise. Let's send a request with requests to see the effect, as shown in the figure below:

 

It doesn't look like a problem.

Now, I'll do some damage, change the age field to a string, and run it again:

 

As expected, the report was wrong.

Now we change the age field back to a number, but directly remove the name field:

 

Wrong again.

In order to prevent users from submitting data against the rules, we must judge all kinds of abnormal data in the interface. Therefore, the code after adding judgment becomes complex:

@app.route('/insert', methods=['POST'])
def insert():
    info = request.json
    name = info.get('name', '')
    if not name:
        return {'success': False, 'msg': 'name Parameter cannot be omitted or empty!'}
    age = info.get('age', 0)
    if not isinstance(age, int):
        return {'success': False, 'msg': 'age Parameter is not a number!'}
    age_after_10_years = age + 10
    msg = f'This person's name is:{name},10 Years later, this person's age:{age_after_10_years}'
    return {'success': True, 'msg': msg}
Copy code

It seems that using Flask can let you write a working project in very short code. But to write a project that can be used normally, you still need to write more code yourself.

Let's take a look at the extent to which the modern web framework: fastapi can simplify this project:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()


class People(BaseModel):
    name: str
    age: int
    address: str
    salary: float
    
@app.post('/insert')
def insert(people: People):
    age_after_10_years = people.age + 10
    msg = f'This person's name is:{people.name},Ten years later, this person's age:{age_after_10_years}'
    return {'success': True, 'msg': msg}
Copy code

We still use requests to send a message to the HTTP interface developed by FastApi. For normal data, normal use:

 

Now let's change the age field to a string:

 

Return a friendly prompt to tell me the type error: the age field is not integer.

Let's try to remove the name field again:

 

The friendly information is returned and the prompt value is wrong: the name field is missing.

In the whole process, the type check is completed by FastApi itself. We save a lot of time.

I have used Flask for four years, but after using FastApi for 5 minutes, I decided not to use Flask in the future.

In retrospect, let's introduce FastApi.

Use pip or pipenv to install FastApi:

pip install fastapi
pipenv install fastapi
 Copy code

After installation, let's complete the first API:

from fastapi import FastAPI

app = FastAPI()


@app.get('/')
def index():
    return {'message': 'You have created it correctly FastApi Service!'}
Copy code

The writing here is almost the same as that of Flask. However, in Flask, we define the decorator of the route as @ app.route('/'). Here it is written as @ app.get('/')

As shown in the figure below:

 

After writing the code, we need to use uvicon to run FastApi. First, use pip or pipenv to install uvicon:

pip install uvicorn
pipenv install uvicorn
 Copy code

Then execute the command:

uvicorn main:app --reload
 Copy code

Where main indicates that our code file is main.py, and app indicates the name of the FastApi object we initialized-- The reload parameter indicates that it takes effect immediately after the code is modified and does not need to be restarted.

After running the command, we visit http://127.0.0.1:8000 You can see that the interface has correctly returned data in JSON format:

 

So how to define a GET method with parameters? Let's write another piece of code:

@app.get('/query/{uid}')
def query(uid):
    msg = f'You inquired uid Is:{uid}'
    return {'success': True, 'msg': msg}
Copy code

After writing the code, we can directly access the new address in the browser and see that the modification has taken effect, as shown in the following figure:

 

What if you want to restrict the uid to be only a number, not a string? You only need to add 4 more characters:

@app.get('/query/{uid}')
def query(uid: int):
    msg = f'You inquired uid Is:{uid}'
    return {'success': True, 'msg': msg}
Copy code

Use type annotation on the parameters of the function query, which is of type int. Now let's access the interface:

 

When the parameter after query is not an integer, an error is reported normally.

Let's take a look at the POST method at the beginning of this article. When using flash, we need to manually verify the format of the data submitted by the user POST and whether the fields are correct.

But when using FastApi, we only need type annotation to solve all problems. First, we import from pydantic import BaseModel, and then inherit the BaseModel to implement the data fields and formats we allow the POST method to submit:

from pydantic import BaseModel

app = FastAPI()


class People(BaseModel):
    name: str
    age: int
    address: str
    salary: float
 Copy code

The People class specifies the four fields and their types through type annotation. Now let's implement the POST method:

@app.post('/insert')
def insert(people: People):
    age_after_10_years = people.age + 10
    msg = f'This person's name is:{people.name},Ten years later, this person's age:{age_after_10_years}'
    return {'success': True, 'msg': msg}
Copy code

The parameter people of the insert function is specified as the people type through the type annotation.

When we submit data by POST, FastApi will automatically verify the data based on the fields defined in People, and return an error message if it is found to be incorrect.

In addition to making it very easy to develop interfaces, FastApi will automatically generate interface documents for us. Everybody visit http://127.0.0.1:8000/docs , you can see that the interface document has been automatically generated:

 

This interface can not only be viewed, but also directly modify sample data on the interface page, send requests, and conduct on-site testing:

 

The above is a minimalist introduction to FastApi. Interested students can refer to its official documents

Finally, let me tell you that FastApi is an asynchronous Web framework, and its speed is very fast. Far more than Flask.

 

FastApi is one of the fastest Web frameworks. The speed can match the interface written by Golang.

Keywords: Python Back-end Programmer

Added by blkraven on Fri, 19 Nov 2021 02:40:08 +0200