Flask understand

I have always used Django for development before, but after changing my job, the new company uses Flask+MongoDB, so I have learned Flask initially.

Flask: One of the most obvious differences between Flask and Django is that Django has a very limited directory structure, so you just need to create an app and write models. Py, views.py, etc. Flask, on the other hand, implements only the core functions of the Web framework (essentially a socket server, and the user’s browser is a socket client). There are a number of third-party components, such as flask-SQLAlchemy for the ORM framework. Flask — Mongoengine is also optional. It’s extensible and customizable, and that’s the best thing about Flask. With all of these third-party components, flask is pretty much Django.

Flask has two core dependency libraries: Werkzeug and Jinja. Werkzeug is responsible for core logic, such as routing, request and reply encapsulation, etc. Jinja is responsible for rendering templates. If you develop Restful apis, the back end only returns JSON data to the front end, so I don’t understand Jinja at all.

The use of the Flask

Install the flask

(venv) incisordeMacBook-Pro:flask-test incisor$ pip3 install flask
Copy the code

Hello World

App. Py files

from flask import Flask

app = Flask(__name__)  Create an instance

@app.route('/')
def hello_world():
    return 'hello world'


if __name__ == '__main__':
    app.run(debug=True)
Copy the code

Start the server with python3 app.py, go to your browser, type http://127.0.0.1:5000/, and you’ll see Hello World.

Flask to write a Restful API

Dumps (), json.dumps(), json.loads() are also available. In contrast to Django, Flask does a pretty good job of supporting Restful data in its native form. JSON is currently the dominant data transfer method for Restful apis, and Flask can convert Python dict or lists into JSON via Jsonify ().

Go straight to the code demo:

from flask import Flask, request, jsonify

app = Flask(__name__)


# assume that this is data stored in the database
USER_LIST = [{'id': 1, 'name': 'zws'.'age': 18}, {'id': 2.'name': 'Tom'.'age': 19}]


@app.route('/user', methods=['GET'])
def get():
    GET request to GET all data
    return jsonify({'code': 200, 'msg': 'ok'.'data': USER_LIST})


if __name__ == '__main__':
    app.run(debug=True)
Copy the code

Flask implements a Restful API for GET requests. POST, PUT, PATCH, and DELETE need to be determined by request. Method. No, Flask also has CBV, so we’ll use the Flask CBV to improve the /user API.

Flask’s CBV needs to inherit the MethodView class

from flask import Flask, jsonify, request
from flask.views import MethodView

app = Flask(__name__)

USER_LIST = [{'id': 1, 'name': 'zws'.'age': 18}, {'id': 2.'name': 'Tom'.'age': 19}]

class UserView(MethodView):

    def get(self):
        return jsonify({'code': 200, 'msg': 'ok'.'data': USER_LIST})

    def post(self):
        # get_json() converts the JSON data from the front end into a Python dict or list
        json_data = request.get_json()
        new_id = len(USER_LIST) + 1
        USER_LIST.append({'id': new_id, **json_data})
        return jsonify({'code': 204, 'msg': 'ok'.'data': USER_LIST[new_id-1]})


@app.route('/', methods=['GET], endpoint='"
If you do not define an endpoint, the default endpoint is the function name of the current view function
app.add_url_rule('/user', view_func=UserView.as_view(name='user'))


if __name__ == '__main__':
    app.run(debug=True)
Copy the code

Json_data = request.get_json() = request.get_json() Request. Get_json () returns None. Get_json () returns None.

def get_json(self, force=False, silent=False, cache=True): ... Omit...if not (force or self.is_json):
        return None
Copy the code

Self.is_json Determines the content-type of the header. If content-type: application/json is set, self.is_json() returns True. There are two ways to handle this: –> Request Settings content-type: Application /json –> the request can be set to True instead of force (force or self.is_json) and one of them will return True, but for specification purposes, It is recommended to set the content-type of the request header, and also to set force=True in request.get_json().

You can see from the code above that you can write Restful apis with MethodView,

Flask-restful extension library to write restful apis

Flask-restfule Flask-restfule

The installation

pip3 install flask-restful
Copy the code

Modify the demo above:

from flask import Flask, jsonify, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)


USER_LIST = [{'id': 1, 'name': 'zws'.'age': 18}, {'id': 2.'name': 'Tom'.'age': 19}]


class UserView(Resource):

    def get(self):
        There is no need to manually call jsonify()
        return {'code': 200, 'msg': 'ok'.'data': USER_LIST}

    def post(self):
        json_data = request.get_json()
        new_id = len(USER_LIST) + 1
        USER_LIST.append({'id': new_id, **json_data})
        return {'code': 204, 'msg': 'ok'.'data': USER_LIST[new_id-1]}


api.add_resource(UserView, '/user')


if __name__ == '__main__':
    app.run(debug=True)
Copy the code

Flask-restful is basically used in this way, by inheriting resources to reflect calls to get and post methods.

MethodView () : dispatch_request() : dispatch_request() : dispatch_request(); Write another document.

Flask development Restful apis are now available for Flask development. After comparison, you can see how much lighter it is than Django. If YOU learn Django and then learn Flask, I feel that you will learn it in a minute.