python flask_ Introduction to restful interface development

Time:2020-9-24

Python version: Python 3.8

First, let’s take a look at the simplest example: when we get to access’ / Hello ‘, we return success

app.py

from flask import Flask
app = Flask(__name__)
from flask_restful import Api,Resource

class HelloWorld(Resource):
    def get(self):
        return 'success'

api.add_resource(HelloWorld, '/hello')

if __name__ == '__main__':
    app.run(port=3000)

Next is the upgrade version. We try to change it to a post request and receive a parameter ‘user’ with simple form validation

from flask import Flask
app = Flask(__name__)
from flask_restful import Api,Resource,reqparse

class HelloWorld(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_ Argument ('user ', type = STR, help = illegal parameter')
        args = parser.parse_args()
        print(args)
        return 'success'

api.add_resource(HelloWorld, '/hello')

if __name__ == '__main__':
    app.run(port=3000)

The next step is how to standardize the returned data of the interface: we define a GetData class and get the data by accessing ‘/ GetData’

from flask import Flask
app = Flask(__name__)
from flask_restful import Api,Resource,reqparse,fields,marshal_with

class GetDatas(Resource):
    resource_fidlds = {
        'title':fields.String,
        'content':fields.String
    }
 @marshal_with(resource_fidlds)
    def get(self):
        Return {'title': 'I am the title','content ':' I am the content '}

api.add_resource(GetDatas, '/getDatas')

if __name__ == '__main__':
    app.run(port=3000)

If you see the above code is confused, let’s give you an example of the data returned by database query

Suppose we have a data model as follows: This is the data model of an article, which simply defines several required fields

#Article table
class Artcle(db.Model):
    __tablename__ = 'artcle'
    id = db.Column(db.Integer,primary_key=True)
    title = db.Column(db.String(60))
    content = db.Column(db.Text)
    author = db.Column(db.String(10))
    create_time = db.Column(db.DateTime)

Next, we simulate the query database and return to JSON

from flask import Flask
app = Flask(__name__)
from flask_restful import Api,Resource,reqparse,fields,marshal_with

class GetDatas(Resource):
    resource_fidlds = {
        'title':fields.String,
        'content':fields.String
    }
 @marshal_with(resource_fidlds)
    def get(self):
        result = Artcle.query.all()
        return result

api.add_resource(GetDatas, '/getDatas')

if __name__ == '__main__':
    app.run(port=3000)

When we visit ‘/ GetData’, we will return {‘title’:’xxx ‘,’content’:’xxx ‘}. Experienced students may find that the process of data conversion in JSON is omitted

This time, it is not a complete demo, so you can not copy and paste +run directly. If you can’t understand it, you can first look at the basic knowledge