Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of Flask running in Python

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "what is the principle of Flask operation in Python". Xiaobian shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "what is the principle of Flask operation in Python" can help you solve the problem.

  All Python Web frameworks adhere to the WSGI protocol, so here's a brief overview of the core concepts of WSGI.

  There is a very important concept in WSGI: every Python Web application is a callable object. In Flask, this object is the app created by app = Flask(name), which is the green Application section in the image below. To run a web application, you must have a web server, such as apache, nginx, or gunicorn in python, which we will talk about below. The WSGIServer provided by werkzeug is the yellow Server part of the figure below.

  How to communicate between Server and Application is the function of WSGI. It specifies the interface of app(environ, start_response), server will call application, and pass it two parameters: environ contains all the information of the request, start_response is the function that needs to be called after the application is processed, and the parameters are status code, response header and error information.

  A very important feature of a WSGI application is that it can be nested. In other words, you can write an application that does what it does by calling another application and returning it (like a proxy). Generally speaking, the last layer of nesting is the business application, and the middle is the middleware. The advantage of this is that it can decouple business logic and other functions, such as current limiting, authentication, serialization, etc., into different middle layers, which are unrelated to business logic and can be maintained independently; and users can dynamically combine different middle layers to meet different requirements.

  Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Flask uses the BSD license. Flask is also known as a "microframework" because it uses a simple core with extensions to add additional functionality. Flask has no default database or form validation tools. Flask, however, retains the flexibility to augment with Flask-extensions: ORM, form validation tools, file uploads, various open authentication technologies. We can understand this, Flask is a core, and other functions are some plug-ins, what function is needed, as long as the corresponding plug-in is found, it can be inserted into the core to achieve the function.

  Flask is how to translate code into Web pages that we can see. First of all, we have to look at the general flow of Web applications. For our Web applications, when the client wants to obtain dynamic resources,(For example, websites written in languages such as ASP and PHP), an HTTP request will be initiated at this time.(For example, using a browser to access a URL), at this time the Web application will perform corresponding business processing in the background of the server (such as operating on the database or performing some calculation operations, etc.), extract the data required by the user, and generate the corresponding HTTP response (of course, if the access is static resources, the server will directly return the resources required by the user, and will not perform business processing). The whole treatment works are as follows:

  In practice, different requests may invoke the same processing logic. HTTP requests with the same business processing logic can be identified by a type of URL. For example, in our blog site, all requests for Articles content can be represented by articles/URLs, where article_id is used to distinguish between different articles. Then define a get_article(article_id) function in the background to obtain the corresponding data of the article. In addition, you need to establish a one-to-one correspondence between URL and function. This is what is called routing distribution in Web development, as shown in the following figure:

  In Flask, route distribution is done using werkzeug, the underlying WSGI library used by Flask (WSGI, full for Web Server Gateway Interface, or Python Web Server Gateway Interface, is a simple and generic interface between Web servers and Web applications defined for Python).

  WSGI divides Web services into two parts: servers and applications. The WGSI server is responsible for only two things related to the network: receiving HTTP requests from browsers and sending HTTP replies to browsers; and the specific processing logic for HTTP requests is performed by calling WSGI applications. The WSGI workflow is shown below:

  In Flask, the code for routing distribution is simple to write, as follows:

#admin logout page @main.route ('/logout') def logout(): dm = DataManager() currentUsers = dm.getUsers('0') print(currentUsers[0]) return render_template('currentUsers.html', users=currentUsers)

  After obtaining the data we need through the business logic function, the server will generate an HTTP response based on this data (for Web applications, it is generally an HTML file that can be directly read and interpreted by our client, that is, the browser). In Web development, the common practice is to transfer the acquired data into an HTML template file provided by Web application, and finally get the HTML response file we need after rendering by template system.

  In general, although the request is different, but the display of the data in the response is the same, popular point is that in addition to the data we request is not the same, other are the same, then we can design a template (except that the data content can be changed, other are fixed HTML files). We take blog site as an example, for different articles, although the specific article content is different, but the content displayed on the page is the same except for the requested data, there are title bars, content bars, etc. That is, for an article, we simply provide an HTML template and pass in different article data to get different HTTP responses. This is called template rendering, as shown below:

  Flask uses Jinja2 template rendering engine for template rendering (Jinja2 is a python based template engine with features similar to PHP smarty, J2ee Freemarker and velocity). It can fully support unicode, and has an integrated sandbox execution environment, widely used. Jinja2 uses the BSD license). The workflow of Jinja2 is shown below:

  In Flask, template rendering code is also very convenient to write, the code is as follows:

@app.route('/articles//') defget_article(article_id):returnrender_template('path/to/template.html', data_needed)

  In Flask, the process of processing a request is to first decide which business logic function to process according to the URL submitted by the user, and then operate in the function to obtain the required data. Then the obtained data is transferred to the corresponding template file, Jinja2 is responsible for rendering the HTTP response content, that is, the HTML file of the HTTP response, and then Flask returns the response content.

  The following is a brief analysis of Flask's operating principle based on an example project. In the example project, the program factory functions and blueprints are used. The project catalogue is structured as follows:

  In the manager.py file, the entry function for project startup is defined:

#Make sure the server only runs the script if it is executed directly by the Python interpreter, not if it is imported as a module. if __name__ == '__main__': #Enable cmd command line # manager.run() app.run(host='0.0.0.0', port=9000, debug=True)

At the same time, factory method instances are created in this file:

app = create_app()

  In the engineering method, the database is configured, the front-end navigation bar is created, and the blueprints created are registered. In the blueprint, authorization, routing and error handling modules are involved.

#construct factory method def create_app(): #here__name__=__main__ app = Flask(__name__) app.url_map.converters['regex'] = RegexConverter #Prevention of cross-site attacks Note: To enhance security, keys should not be written directly into code, but should be stored in environment variables # app.config['SECRET_KEY'] = 'hard to guess string SUNNY2017' # app.secret_key = 'Sunny123456' # Flask provides read external files app.config.from_pyfile('config') # basedir = os.path.abspath(os.path.dirname(__file__)) # print(basedir) #Configure database connections app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://lmapp:lmapp@localhost/smp' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True nav.register_element ('top ', Navbar(u'APP ', View(u'currently online','main. index'), View(u'all users','main.all_users'), View(u'logout','main. logout'), View(u'change password','main.chgpwd'), )) nav.init_app(app) db.init_app(app) bootstrap.init_app(app) # init_views(app) from .auth import auth as auth_blueprint from .main import main as main_blueprint #Register blueprints url_prefix ='/auth' app.register_blueprint(auth_blueprint,) app.register_blueprint(main_blueprint, static_folder='static') Return app The content of "What is the principle of Flask operation in Python" is introduced here. Thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the industry information channel. Xiaobian will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report