Flask components, pits you must understand

This article is a summary of many problems I encountered when using flask components for development. You can refer to it when choosing flask development technology.


1. Flask does not support concurrency. If you want to deploy on the server, you must learn the knowledge of deploying the server and uwsgi.

But for more explanation, just look at the source code.


2. It is strongly recommended that you do not use flask-login, because it is really rubbish. It's too easy to get bugs.

Flask-login is not simple, and the mechanism inside is very complicated. Using the session component that comes with native flask can completely replace it. After all, as an open source component, flask-login may still have big bugs.


3. Whenever possible, I strongly recommend that you use flask-sqlalchemy instead of sqlalchemy.

Both libraries have been used. In essence, flask-sqlalchemy is a flask-style sqlalchemy, which is very easy to use.


4. The choice of login judgment should consider whether to use session-cookie or token.

This is your flexible choice.


5. For exception handling, it is strongly recommended to use the official level exception handling. And flask encapsulates a lot of exception handling things, it is recommended to eat according to the official document.


6. If you use flask-restful, then restful will automatically capture all exceptions that occur in all view functions, so all custom exception handling functions for app will be invalid. Simply put, it is to write like this:

class MyApi(Api):
    """
    自定义Api类
    """
    def handle_error(self, e):
        # deal with the HTTPException
        if isinstance(e, HTTPException):
            return jsonify({
    
    
                'message': getattr(e, 'description', HTTP_STATUS_CODES.get(e.code, 'Unknown Error')),
                'code': e.code
            }), e.code
        # deal with the python core exception
        # we don't need to use "try" to catch the exception
        if not getattr(e, 'message', None):
            current_app.logger.error(e)
            return jsonify({
    
    
                'message': 'Server has encountered some errors.',
                'code': 500
            }), 500
        # deal with the specific custom exceptions
        return jsonify(**e.kwargs), e.status_code

7. When considering flask-apscheduler, you must first know that the documentation of this library is very rubbish, and you must understand that the JOB fields inside cannot be changed, that is to say, the fields inside the JOB stored in the database cannot be customized unless modified source code.

Really a SB library.


8. When using flask to develop, you must pay attention to the directory structure, otherwise it will be very troublesome. The official document gives the best practice of the directory. You can refer to it.

Guess you like

Origin blog.csdn.net/m0_51156601/article/details/127159629