1 what is flash?
Flask was originally an April Fool's Day joke by author Armin Ronacher on April 1, 2010, but later became very popular and became a formal web framework written in python
Flask is a Web micro framework written in Python, which allows us to quickly implement a website or Web service using Python language. Before introducing flask, let's talk about its connection and difference with Django. Django is a large and comprehensive Web framework with many built-in modules. Flask is a small and refined lightweight framework, Django has large and comprehensive functions, and flask only contains basic configurations, Django's one-stop solution allows developers not to spend a lot of time choosing the application infrastructure before development. Django has built-in functions such as templates, forms, routing, basic database management and so on. On the contrary, flask is only a kernel, which depends on two external libraries by default: Jinja2 template engine and WSGI tool set - Werkzeug. The use feature of flask is that basically all tool uses depend on import to expand, and flask only retains the core functions of Web development.
WSGI (Web Server Gateway Interface) is a standard used in Python to specify how web servers communicate with Python web servers and python web programs. It is essentially a socket server. The Werkzeug module is a concrete implementation of WSGI
Key words: a Python micro web framework, one core and two libraries (Jinja2 template engine and WSGI toolset)
2 why flash?
The performance of flash basically meets the needs of general web development, and it is superior to other web frameworks in flexibility and scalability, and has a very high degree of fit to various databases
Key words: 1. The performance basically meets the requirements. 2. It is flexible and expandable. 3. It has a high degree of fit to various databases.
4. In the real production environment, the development of small projects is fast and the design of large projects is flexible
3 pre school preparation: Virtual Environment
3.1 what is a virtual environment?
A virtual environment is an isolated Python interpreter environment. By creating a virtual environment, you can have an independent Python interpreter environment, which is equivalent to copying a private copy of the global Python interpreter environment. The advantage of this is that you can create an independent Python interpreter environment for each project, because different projects often rely on different versions of libraries or Python versions. Using the virtual environment can keep the global Python interpreter environment clean, avoid the confusion of packages and versions, and easily distinguish and record the dependencies of each project. The so-called environment traceability is also a file. Since it is a file, it supports copying to various platforms, so it also improves the portability to reproduce the dependent environment in the new environment.
For example:
Example 1: if you have many projects at the same time, a crawler project, a Flask project and a Django project in one environment, it is inevitable that the management of related third-party libraries will be confused.
Example 2: if you have two flash projects, but the flash versions of the two projects are inconsistent, there will be version conflicts
Keywords: 1. A private copy of Python interpreter 2. It solves the confusion of package management, version conflict and improves portability
3.2 how to use virtual environment?
3.2.1 building a virtual environment
In the installation process of windows development environment, we use virtualenv virtual development environment. First, install the dependencies of related packages
pip install virtualenvwrapper-win
Using the installed modules, we create a virtual environment
##Note: this' first '_ 01_ Env '' is our own name for the virtual environment, and we need to record the installation path in figure (1) below. We need to use it later.
mkvirtualenv first_01_env
Other commands related to virtual environment:
01. Switch to the specified virtual environment: note that we need to use the workon command to enter the virtual environment, but the first successful installation will automatically enter the virtual environment.
workon first_01_env
02. Exit the virtual environment
deactivate
03. Delete the specified virtual environment
rmvirtaulenv first_01_env
04. List all virtual environments:
lsvirtualenv
05. Enter the directory where the virtual environment is located:
cdvirtualenv
3.2.1 install our flash module in the virtual environment
pip install flask
Collecting flask ... Successfully installed Jinja2-2.10 MarkupSafe-1.1.0 Werkzeug-0.14.1 click-7.0 flask-1.0.2 itsdangerous-1.1.0
As can be seen from the above successfully installed output, in addition to the Flask package, there are also five dependent packages installed at the same time. Their main descriptions are shown in table (1-1).
Package name and version | function |
---|---|
Jinja2-2.10 | Render template engine Toolset |
MarkupSafe-1.1.0 | HTML escape rules can be recognized. HTML character escape Toolset |
Werkzeug-0.14.1 | The underlying Library of Web framework provides the functions of request and response and development server, which is called WSGI tool set for short |
click-7.0 | Command line Toolset |
itsdangerous-1.1.0 | Encryption Toolset |
Table (1-1)
First, I have an impression of these five libraries, and then I will apply them in specific practical applications.
✔ Tip: these libraries were developed by the flash team
4 start our first flash program
Here, we use the pycharm editor to learn flash. We won't repeat the installation of pycharm.
4.1 create a flash program
The specific operation is shown in figure (a) - figure (d)
First step
Figure (a)
Step 2
Figure (b)
Step 3
! Note: if the virtual environment path cannot be found, you can refer to other commands of the virtual environment
lsvirtualenv # List all virtual environments workon first_01_env # Switch to the specified virtual environment cdvirtualenv # Switch to the specified virtual environment path, which is the path we want
Figure (c)
Step 4
Figure (d)
4.2 interpretation of flash program
4.2.1 detailed description of project directory:
"Static folder" is used to store various static files css, js, pictures, etc
"templates folder" is used to store html template files
"app.py" is our main file, which needs to be started to start the project
Note that the name of the app.py file can be freely named, except for the name of flash.py, which conflicts with the flash library
Main file app.py file code
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello World!' if __name__ == '__main__': app.run()
4.2.2 the code is divided into three parts:
Part I
from flask import Flask app = Flask(__name__)
Import the installed flash package. Import the flash class through the flash package. The flash class is the core of flash. Instantiate the flash class to an instantiated object app.
__ name__ This special parameter: Python will assign it according to the module__ name__ The corresponding value of the variable. For our program (app.py), this value is app.
@app.route('/') def hello_world(): return 'Hello World!'
If you know about other web frameworks, I believe you have seen some ways. Yes, this @ app.route('/') is used to match the url. In our flash, it is implemented as a decorator. The decorator also refers to the object instantiated from the core class above.
So what is the following function if routing? Yes, it is our view function. If the route is matched, it will trigger the execution of our view function, and return the specific data to the front end or mobile end.
It doesn't matter if we don't understand it very well. We'll have an impression first. We'll explain the use of routing and view functions in detail in the next chapter
Part III
if __name__ == '__main__': app.run()
Regardless of the logical judgment, first look at the app.run(), app.run() source code. If you go on to read the source code, it is not difficult to find that the default ip + port is defined internally as 127.0.0.1:5000, and werkzeug.serving is called to create a development server for us (provided by the dependency package Werkzeug). Friends who have a certain understanding of sockets, Its internal function is to do a circular listening function for interaction
Key words: app.run() enables the flash program to run in the development environment, and the default ip and port are 127.0.0.1:5000.
def run(self, host=None, port=None, debug=None, load_dotenv=True, **options): ... _host ='127.0.0.1' _port = 5000 ... host = host or sn_host or _host port = int(port or sn_port or _port) ... from werkzeug.serving import run_simple try: run_simple(host, port, self, **options) finally: # reset the first request information if the development server # reset normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False
In the third part, there is also an if judgment. What is the function of this judgment? python based friends are probably familiar with this writing method. If logic judgment can only be executed when this file is an execution file. Why is it designed like this? In the development environment, we use app.py as the execution file, but in the real production environment, this file will be used as the called file, and app.run() will not be used for listening allocation in the real generation environment. The reason is that the performance is too low,
Key words: it ensures that app.run() is only used in the development environment and does not affect the real production environment.
Three part crosstalk
Import the core class of Flask to instantiate the object app, and then distribute the app as a decorator to the following view function using the matching url. Then executing the page will trigger the app to call the run() method to run the whole project.
4.2.2.1 introduction to Werkzeug
werkzeug is a WSGI toolkit, which can be used as the underlying Library of a Web framework. Here, werkzeug is neither a Web server nor a Web framework, but a toolkit. The official introduction says it is a WSGI toolkit, which can be used as the underlying Library of a Web framework because it encapsulates many things of the Web framework, such as Request, Response, etc.
Code example:
from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response('Hello World!') if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 4000, hello)
understand
See if this wekzeug is particularly like our flash code. Yes, our flash depends on this werkzeug module. The wekzeug module implements the function of the socket server. Hello must run in parentheses before executing the code in hello. In our flash, app.run() will call run_simple(host, port, self, **options) replaces the Hello of the above code example with self, that is, app. app() will trigger the flash class__ call__ method.
So the entrance to the flash program is__ call__ Method, and__ call__ Method returns self.wsgi_app(environ, start_response), so the execution process of the whole program is in self.wsgi_app(environ, start_response)
Subsection:
1 app.run() call werkzeug.serving of run_simple(host, port, self, **options)
2 self()Equivalent to app(), app()call Flask Class__call__method
3 Flask Class__call__Method returned self.wsgi_app(environ, start_response)
4 flask The execution process of the program is self.wsgi_app(environ, start_response)in
Specific code:
def run(self, host=None, port=None, debug=None, load_dotenv=True, **options): ... _host ='127.0.0.1' _port = 5000 ... host = host or sn_host or _host port = int(port or sn_port or _port) ... from werkzeug.serving import run_simple try: run_simple(host, port, self, **options) finally: # reset the first request information if the development server # reset normally. This makes it possible to restart the server # without reloader and that stuff from an interactive shell. self._got_first_request = False
... def __call__(self, environ, start_response): """The WSGI server calls the Flask application object as the WSGI application. This calls :meth:`wsgi_app` which can be wrapped to applying middleware.""" return self.wsgi_app(environ, start_response) ... def wsgi_app(self, environ, start_response): ctx = self.request_context(environ) error = None try: try: ctx.push() response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: error = sys.exc_info()[1] raise return response(environ, start_response) finally: if self.should_ignore_error(error): error = None ctx.auto_pop(error) ...
key word:
- Werkzeug is a WSGI toolkit, which is essentially a socket server.
- Flash is based on Werkzeug. Flash only retains the core functions of web development.
- Flash is executed in def wsgi_app(self, environ, start_response):
4.2.3 operation items
Run our flash project, as shown in figure (2), or right-click run in app.py to start the project
Figure (2)
Then visit http://127.0.0.1:5000/ See figure (3)
Figure (3)
! It is emphasized that we should not create a flash project with the flash shortcut provided by pycharm in the future. The shortcut above is easy to explain and understand. It is more recommended to directly create an empty python project in the real production environment
4.2.4 detailed explanation of DEBUG mode
4.3.4.1 DEBUG mode solves two problems.
-
If an exception occurs in the flash code, we will not prompt the specific error message in the browser. After the debug mode is turned on, we will send the specific error message to the browser.
-
If the flash code is modified, the project must be restarted to make the modified code effective. After the debug mode is enabled, if we modify the code, as long as ctrl+s, our flash project will be automatically reloaded without manually loading the whole website.
Example 1:
In this case, there is obviously an array out of bounds problem
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): a = [1,2,3,4] print(a[4]) return "hello" if __name__ == '__main__': app.run()
Access is shown in figure (4)
Figure (4)
As shown in Figure 4, it only prompts the internal error of the server, and does not prompt the specific error reason
OK, let's add a parameter for app.run() and rewrite it to app.run(debug=True)
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): a = [1,2,3,4] print(a[4]) return "hello" if __name__ == '__main__': app.run(debug=True)
Visit again as shown in figure (5)
Figure (5)
We see the specific error message IndexError: list index out of range
Pressing ctrl+s every time you modify the code will automatically reload the flash project code. There is no demonstration here
! It is emphasized that the project should not be created by creating false quickly, just like creating an ordinary python project, or by opening an empty file, otherwise debug=True will be invalid
4.2.4.2 four ways to start DEBUG
First kind
from flask import Flask app = Flask(__name__) @app.route('/') def hello(): a = [1,2,3,4] print(a[4]) return "hello" if __name__ == '__main__': app.run(debug=True) # set up
Second
from flask import Flask app = Flask(__name__) app.debug = True # set up @app.route('/') def hello(): a = [1,2,3,4] print(a[4]) return "hello" if __name__ == '__main__': app.run()
Third
from flask import Flask app = Flask(__name__) app.config.update(DEBUG=True) # set up @app.route('/') def hello(): a = [1,2,3,4] print(a[4]) return "hello" if __name__ == '__main__': app.run()
Fourth
You need to create another config.py in the directory where app.py is located. As we learn, we will use this configuration file more and more to configure our flash project. Note that the configuration information is generally capitalized.
config.py
DEBUG = True
app.py
from flask import Flask import config # Import app = Flask(__name__) app.config.from_object(config) # set up @app.route('/') def hello(): a = [1,2,3,4] print(a[4]) return "hello" if __name__ == '__main__': app.run()
app.config essentially inherits the dictionary and is an object of a subclass of the dictionary, as shown in figure (6)
Figure (6)
4.2.4.3 the PIN code of debug can be used for debugging code on the browser side (not recommended, just understand it)
* Debugger PIN: 648-906-962
Figure (7)
It can support debugging on the web side