In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand the Flask framework in Python operation and maintenance development? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
I believe I have struggled with this question: how to master flask thoroughly?
Flask is a lightweight Web application framework written in Python. Its WSGI toolbox uses Werkzeug, and the template engine uses Jinja2. Flask uses BSD authorization.
Flask is also called "microframework" because it uses a simple core and adds other functions with extension. Flask does not have database and form validation tools that are used by default.
Today, we have invited an immobile teacher who has been engaged in Python development for many years and asked him to bring us the front line of flask development.
Sharing begins
Hello, everyone. Now let's share flask development. Let's take a look at the content of this sharing:
1. Introduction of Flask Web framework
Flask is a miniature web framework, the framework itself is very concise, miniature does not mean its weak function, the core code is based on Werkzeug, Jinja 2 these two libraries, it is in the form of plug-ins for functional expansion, and plug-ins are easy to install and use, and can develop their own extensions
Similar to other web frameworks, request (request), route (route) and response (response) in flask constitute a complete basic http process.
2. It is very easy to use as an entry-level flask framework
Once you understand its basic structure, you can quickly develop MVC, or use it as a back-end restfulApi to respond to data.
* * step: let's first install flask in a virtual environment
Virtual environment, which completely isolates the current running environment from the system's python environment. Here we use pyenv as a library to build the environment.
Take the centos system as an example to install a virtual environment:
1 、 yum install zlib-devel bzip2 bzip2-devel readline-devel sqlite sqlite-devel openssl-devel
2. Curl-L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer
| | bash |
Configure environment variables and add the following to ~ / .bash_profile:
Export PATH= "~ / .pyenv / bin:$PATH" eval "$(pyenv init -)" eval "$(pyenv virtualenv-init -)"
Step 2: activate this pyenv when creating a virtual environment
1. The version of python that usually comes with the system is python2.7.10.
2. We download a python version 2.7.12 by ourselves.
3. Mirror source using sohu: http://mirrors.sohu.com/python/
Find the package with python version 2.7.12 and download it locally.
Why do I need to use virtual environments? Because the virtual environment is independent for each python environment, when multiple projects can be run on a single machine, the environment of each project is isolated and does not produce dependencies.
4. If you need other versions, you can download the corresponding version and put it under the ~ / .pyenv / cache folder (if the cache folder does not exist, create it yourself)
5. Then execute the pyenv install version number to install the corresponding python version: pyenv install 2.7.12
6. After successfully installing version 2.7.12, create a python virtual environment with a completely isolated directory:
Pyenv virtualenv 2.7.12 venv27
Mkdir-pv virtu
Cd virtu pyenv local venv27 cd.. Cd virtu automatically activates the venv27 environment
Step 3: install pip
Pip is a tool for installing python third-party libraries
Sudo yum-y install epel-release (install yum package extension)
Sudo yum-y install pip
Use Aliyun's python package to accelerate pip installation
Pip configures Ali Cloud image:
Mkdir / .pip
Vim ~ / .pip / pip.conf, enter the following
[global] index-url= http://mirrors.aliyun.com/pypi/simple/
Trusted-host=mirrors.aliyun.com
Step 4: install flask:
Cd vnvn27 (the virtual environment you just built, switched to a completely virtual environment)
Pip install flask
Pip freeze lists the currently installed third-party python libraries and versions
Run the python terminal, import flask, to test whether the flask installation is successful
2.0:wsgi specification
Python uses the wsgi gateway for Web development. Flask is based on the wsgi gateway, the app of the instance in flask, also known as a wsgi application.
Wsgi is a gateway protocol specification defined in python, which is explained by pep333: https://www.python.org/dev/peps/pep-0333/
From wsgiref.simple_server import make_server
The wsgiref package is a reference for implementing the wsgi standard, which we can use for debugging. This package is generally used in a test environment and is not recommended in a production environment.
Simple_server implements a simple http server that we can use to run a wsgi application
2.1:wsgi Specification 2
For the following example, we can use the package wsgiref to implement a simple wsgi web framework to understand its workflow:
2.2:wsgi Specification 3
In the above code, we simply implement a wsgiweb framework using the wsgiref package, in which we match the corresponding handler functions in the router dictionary according to the url suffix obtained from the passed env
The Env parameter contains the information requested by the client and the environment information of the server, which can be printed out to see the variables contained in it.
When the Start_response function is introduced into the runserver application as a parameter, it must be responded by start_response (status,header), which is defined by the gateway interface.
As can be seen in the above, the function of wsgi is a bridge between the web server and the web application, the web server listens and forwards the client request to implement the wsgi specification interface processing, the wsgi then transfers the request to the upper web application processing, the web application processing is completed and the response is generated and returned to the wsgi interface, and then the web server returns the received response to the client.
2.3: a most basic application
The Flask framework is also a web framework implemented according to the above specification. We can take a look at the above encapsulation in the flask source code, but it does a higher level of abstraction.
You can see that the above start_respones is encapsulated using wsgi_app and the magic method _ _ call__ in the flask source code.
Next, run a hello wordl with flask
2.4: a most basic Application Analysis
/ usr/bin/env python from Flask import flask app = Flask (_ _ name__) @ app.route ('/') def index (): return 'Hello Worldwaters' if _ _ name__ ='_ _ main__': app.run () python hello.py
2.5: most basic applications
The app = Flask (_ _ name__) code uses the Flask class to generate an application instance
@ app.route ('/') def index (): return 'hello world'
In a http process, the request comes from the client, and the http server (nginx,Apache) again forwards the request to the flask application instance app,@app.route ('/), which maps the corresponding relationship between the url link and a python function. We call the index function the view function.
For example, visit 192.168.1.19
-"app.route ('/')
Visit 192.168.1.19/blog
-"app.route ('/ blog')"
2.6Varible url
In general business, url is dynamically variable. In flask, we set variable url in this way.
@ app.route ('/ hello/') def hello (name): return 'hello {}' .format (name)
Example:
Visit 192.168.1.19/hello/jack
Visit 192.168.1.19/hello/rose
The part enclosed in angle brackets represents the variable part of the url corresponding to the python handler.
The following three types are commonly used to define variable types
、 、
2.7Varible url custom installer
To define a variable url, in addition to the above string, there are the following three types of int, float, and path. In addition, flask can also customize the converter through the BaseConverter class in werkzeug.
Customize a converter here
Fromwerkzeug.routing import BaseConverter classListConverter (BaseConverter): def to_python (self, value): return value.split ('+') def to_url (self, values): return'+'.join (BaseConverter.to_url (value) for value in values)
Add the custom converter to the app application url_map, and when the client enters parameters, it can be converted with the delimiter we set by ourselves.
App.url_map.converters ['list'] = ListConverter @ app.route (' / home/') def home (subs): # use the custom type htm =''for sub in subs: htm + =' {} '.format (sub) return htm
In a production environment, the general process of developing an application using python from client to server is as follows:
Request in flask, which is one of the most important features in web development
Getting started with 3.0 Flask: request
From flask import request @ app.route ('/ hi') def hi (): name = request.args.get ('name') return' hi {} '.format (name)
Visit:
192.168.1.19/hi?name=mike
The request object in flask encapsulates the request parameters of the client
We can try to print (request.__dict__) to look at the request context environment variables
The request request object is a global object encapsulated within flask. This object is thread isolated and must be run in the context of the current request. If it runs directly, it will report an error. It looks for the current request through localproxy in the localstack data structure in the werkzeug module.
Common request client variables
Request.args gets the query string transferred from the client url
Request.form gets the information submitted from the client form
Request.json gets the json string obtained from the client from the request body
Request.method gets the request method used by the client
Request.files gets the file requested from the client
3.1getting started with Flask: response and conversation
From flask import make_respones
Flask encapsulates make_response as the client response, returns http header information, status code, etc., resp = make_respone ('hello'.encode ()), resp.set_cookie (' name', 'jack'), and returns resp, so you can manually and flexibly add cookie
Sessions are divided into client and server. Client-based cookies is encapsulated in from flask importsession. Examples are as follows:
The default configuration of flask and the configuration variables written in our project are saved in the app.config object. In general, some configurations in flask are as follows
4.1 read-in configuration in flask
App = Flask (_ _ name__)
App.config.from_object ('yourapplication.default_settings')
App.config.from_pyfile ('config.cfg')
Both of the above can add configuration files to app applications, where the app.config.from_object () method looks for configurations with configuration files as classes
Use the function to encapsulate the configuration file into the app, so that you can distinguish the configuration file of the development environment from the production environment according to the parameters.
4.2 Factory method to create app
What is the factory method? The factory method is a design pattern, which can be simply understood as creating a flask app object in batches through a function and generating different app according to different parameters.
4.3 Why do I need a factory method to create an app?
When you need to run app, you can pass parameters through the factory method to generate different app objects, easily test different app, and generate multiple app for request processing, traffic load, etc., as illustrated by the following example
5.0 Hook function
The function of the hook function in flask is to register the decorated function with app and execute it at different stages.
App.first_request: execute before * requests
App.before_request: executes before each request, and can be used to encapsulate intermediate keys, similar to django middleware
App.after_request: execute after each request
App.teardown_appcontext: regardless of whether an exception occurs or not, it will be executed after each request
App.errorhandler: accepts the status code and customizes the error handling information page
5.1Hook function before_request
5.2 hook function errorhandler
5.3 Blueprint
The blueprint modularizes the application, which can easily separate different functions and routes, and is easy to maintain. The blueprint is based on the same url prefix.
View functions with similar functions are combined as components of the blueprint to split the application, which greatly simplifies the complexity of large-scale applications. The blueprint is registered in the app object, and the blueprint is used much like app.
Blueprints provide template filters, static files, templates, and other features
5.4 Blueprint Generation
Divide these similar functions of user into a blueprint module. Note that the blueprint file cannot have the same name as the blueprint object, otherwise it will conflict with the error report.
5.5 Blueprint Registration
V when the above user is instantiated, this must be registered in the app application for the blueprint to take effect. Url_prefix is the url suffix added by the custom.
6.0flask extension usage
V flask develops extended functions in the form of plug-ins, in which many excellent third-party plug-ins can be used directly to improve development efficiency. Common plug-ins used in project development are flask_sqlachemy, flask_redis, flask_login, flask_admin and so on.
V plug-in installation generally uses pip install, which can be installed
V the following example flask_sqlachemy is used. Flask_sqlachemy is a flask plug-in for sqlalchemy, and sqlalchemy is a well-known industrial orm framework in python.
6.1flask_sqlalchemy
V instantiate flask_sqlalchemy, generate db object and initialize it to app
6.2flask plug-in initialization
V because the db object needs to read the configuration in the app application and relies on the app context to work, the extensions such as the above db object are initialized app, and the binding is completed before each app startup
6.3 flask_sqlalchemy definition model
Using the above db object, the model field inherits db.Model, which represents the model layer in mvc, which is used for database table field mapping and association, data writing and saving, etc.
6.4 flask_sqlalchemy for user authentication
Applications can be easily developed using flask, and each web framework has its own advantages and disadvantages. For the needs of modern web development, micro-framework is very suitable for rapid iterative development. The way to understand * is practice. You can carry out a simple application development based on the above general understanding of flask.
This is the answer to the question about how to understand the Flask framework in the development of Python operation and maintenance. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.