Environmental installation
Environmental installation
1. Review the virtual environment and pip commands
Remember these commands
# 虚拟环境
mkvirtualenv # 创建虚拟环境
rmvirtualenv # 删除虚拟环境
workon # 进入虚拟环境、查看所有虚拟环境
deactivate # 退出虚拟环境
# pip
pip install # 安装依赖包
pip uninstall # 卸载依赖包
pip list # 查看已安装的依赖包
pip freeze # 冻结当前环境的依赖包
2. Create a virtual environment
Create a virtual environment to be networked
mkvirtualenv flask -p python3
Note the need for networking
3. Install Flask
Use flask 1.0.2 version, pay attention to the need for networking
The following instructions will install the latest version
pip install flask
HelloWorld program
1 goal
Master the way of writing flask programs
2 thinking
Remember how to start writing Django programs?
Flask does not constrain the file structure
3 Flask program writing
The following program is a flask application to
create the helloworld.py file
Create objects to complete the view, routing, request, and response management
# 导入Flask类
from flask import Flask
#Flask类接收一个参数__name__
app = Flask(__name__)
# 装饰器的作用是将路由映射到视图函数index
@app.route('/')
def index():
return 'Hello World'
# Flask应用程序实例的run方法启动WEB服务器
if __name__ == '__main__':
app.run()
4 Start and run
- Run manually
python helloworld.py
- pycharm run
Just run a normal python program like normal.
Parameter Description
- Initialization parameters of the Flask object
- Application configuration parameters
- app.run() running parameters
1 Flask object initialization parameters
When the Flask program instance is created, it needs to pass in the package (module) specified by the current Flask program by default. Next, let's take a detailed look at some of the parameters that we need to pay attention to when the Flask application is created:
- import_name
- Flask where the program package (module), pass name can
- It can determine the path that Flask looks for when accessing static files
- Filling in __name__ will use the direct directory where the entry file is located as the starting point for finding static resources
- Pass a string
- static_url_path
- Static file access path, you don’t need to pass it, the default is: /static_folder
- static_folder
- The folder where static files are stored, you don’t need to upload it, the default is static
- template_folder
- The folder where the template file is stored, you don’t need to upload it, the default is templates
-
Flask("django") regards the directory where this module is located as the home directory -
Can access static resources
-
static_url_path,
such as passing in /s to visit /s/1.png, can also access static resources -
The last two parameters can be filled in absolute path and relative path, the current directory is under the project main directory
Under the default parameters
app = Flask(__name__)
File Directory
----
|---static
| |--- 1.png
|---helloworld.py
You can access the picture by visiting 127.0.0.1:5000/static/1.png
In the case of modifying parameters
app = Flask(__name__, static_url_path='/url_path_param', static_folder='folder_param')
File Directory
----
|---folder_param # 此处目录名变化
| |--- 1.png
|---helloworld.py
You can access the picture by visiting 127.0.0.1:5000/url_path_param/1.png
2 Application configuration parameters
For Flask object initialization parameters, only the properties of Flask itself are set, such as:
- Where does Flask read static files from
- Where does Flask read template files from
- ...
Wait.
The application configuration parameters set the relevant information of a Web application project, such as:
- Database connection information
- Log configuration information
- Custom configuration information
- ...
Wait
effect
Centrally manage all configuration information of the project
How to use
Django puts all configuration information in the settings.py file, but Flask is different.
Flask saves the configuration information to the app.config attribute, which can be operated according to the dictionary type. However, no error will be reported when the dictionary takes values in square brackets
Read
- app.config.get(name)
- app.config[name]
Set up
The following three methods are mainly used:
- Load from configuration object
app.config.from_object(配置对象)
class DefaultConfig(object):
"""默认配置,可以写好多类属性,加载后将会以键值对的方式进行存储到app中"""
SECRET_KEY = 'TPmi4aLWRbyVq8zu9v82dWYW1'
app = Flask(__name__)
app.config.from_object(DefaultConfig)
@app.route("/")
def index():
print(app.config['SECRET_KEY'])
return "hello world"
Application scenarios:
Write in the program code as the default configuration
Can inherit
class DevelopmentConfig(DefaultConfig):
DEBUG=True
- Load from configuration file
app.config.from_pyfile(配置文件)
Create a new configuration file setting.py
SECRET_KEY = 'TPmi4aLWRbyVq8zu9v82dWYW1'
In the Flask program file
app = Flask(__name__)
app.config.from_pyfile('setting.py')
@app.route("/")
def index():
print(app.config['SECRET_KEY'])
return "hello world"
Application scenarios:
Use a fixed configuration file in the project
- Load from environment variables
Environment variables generally refer to some parameters used in the operating system to specify the operating environment of the operating system , such as the location of the temporary folder and the location of the system folder. An environment variable is an object with a specific name in the operating system, which contains information that will be used by one or more applications.
In popular understanding, environment variables are the values of variables that we set in the operating system and are saved by the operating system.
The way to set and read environment variables in the Linux system is as follows: It is
customary to capitalize environment variables
in the terminal. The environment variables set in the terminal are only valid in the current terminal, and pycharm will open a new terminal every time it runs, so the previous environment variables are Run will not be effective
export 变量名=变量值 # 设置
echo $变量名 # 读取
# 例如
export ITCAST=python
echo $ITCAST
The essence of Flask using environment variables to load the configuration is to find the configuration file through the value of the environment variable , and then read the information of the configuration file. Its use is
app.config.from_envvar('环境变量名')
The value of the environment variable is the absolute path of the configuration file
First execute the following command in the terminal
export PROJECT_SETTING='~/setting.py'
再运行如下代码
This code is to find the configuration information in the file pointed to by PROJECT_SETTING, and it will look for the file with the project main directory as the starting point
app = Flask(__name__)
app.config.from_envvar('PROJECT_SETTING', silent=True)
@app.route("/")
def index():
print(app.config['SECRET_KEY'])
return "hello world"
About silent
explanation:
Indicates whether an exception is thrown when the corresponding value is not set in the system environment variable
- False means unquiet processing, an error notification will be reported when there is no value, the default is False
- True means quiet processing, even if there is no value, Flask will continue to run normally. The way
Pycharm sets environment variables when running
You can also add pycharm directly in the input box and
these environment variables will be added before execution
Application scenarios:
The address of the configuration file is not fixed;
Don't want to expose the real configuration file address in the code, only the real configuration file information is available on the server running the code.
Common ways in the project
Load from the configuration object:
Advantages: Inheritance, easy to add or modify attributes
Disadvantages: Sensitive data will be exposed in the code, such as secret keys, which may be stolen, causing data leakage.
Application scenario: Write default configuration, in order to preserve fields and values You can write it
at will. Load from the configuration file:
Advantages: independent files protect sensitive data, you can write an absolute path, and put the configuration file outside of the code.
Disadvantage: You may need to change the code when you put it on different machines.
Regardless of flexibility, only confidentiality is considered, configuration file + absolute path can be used
Use environment variables:
Advantages: Set environment variables, you don’t need to modify the code, specify environment variables
Disadvantages: remember to set environment variables
The configuration object should be used to load the default configuration to ensure that no error will be reported when this configuration is not set. Specify the path of the configuration file in the environment variable and write the real sensitive information in the configuration file.
If there is a default configuration, it will be overwritten for the second time.
Often use factory mode to create Flask app, and use configuration objects and environment variables to load configuration
DEBUG can control the project to run in debug mode, but the new version of flask generally means that the debug mode is written through this
- Use the configuration object to load the default configuration
- Use environment variables to load sensitive configuration information that you don't want to appear in the code
def create_flask_app(config):
"""
创建Flask应用
:param config: 配置对象
:return: Flask应用
"""
app = Flask(__name__)
app.config.from_object(config)
# 从环境变量指向的配置文件中读取的配置信息会覆盖掉从配置对象中加载的同名参数
app.config.from_envvar("PROJECT_SETTING", silent=True)
return app
class DefaultConfig(object):
"""默认配置"""
SECRET_KEY = 'itcast1'
class DevelopmentConfig(DefaultConfig):
DEBUG=True
# app = create_flask_app(DefaultConfig)
app = create_flask_app(DevelopmentConfig)
@app.route("/")
def index():
print(app.config['SECRET_KEY'])
return "hello world"
3 app.run parameters (as an understanding)
The old version of flask has this method, and the new version uses the command line to start.
You can specify the host IP address, port, and whether to open the debug mode.
app.run(host="0.0.0.0", port=5000, debug = True)
About DEBUG debugging mode
- The server can be automatically restarted after the program code is modified
- When there is a related error on the server, the error message can be directly returned to the front end for display
How the development server runs
After version 1.0, Flask adjusted the startup mode of the development server, from code writing app.run()
statements to command flask run
startup.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
# 程序中不用再写app.run()
1 Terminal start
The terminal is started, no need to write app.run() in the code.
flask run will read the environment variables of FLASK_APP. You
can add .py or not. .py is treated as a file, if not, it is treated as a module
$ export FLASK_APP=helloworld
$ flask run
* Running on http://127.0.0.1:5000/
Description
-
The environment variable FLASK_APP indicates the startup instance of flask
-
flask run -h 0.0.0.0 -p 8000
Bind address port -
flask run --help
Get help -
Control of production mode and development mode
FLASK_ENV
Specify by environment variableexport FLASK_ENV=production
Run in production mode, if not specified, it will default to this modeexport FLASK_ENV=development
Benefits of running in development mode
: the code does not need to be changed, the code can be run in different ways through commands
Expand
$ export FLASK_APP=helloworld
$ python -m flask run
* Running on http://127.0.0.1:5000/
2 Pycharm start
Setting environment variables The
new version of pycharm runs under the module name
The old version of Pycharm
does not set the settings , and an error will be reported here, but it does not matter, it can also run normally
notes
-
The request hook in flask has the same meaning as the middleware in Django
-
After creating the project, first set up the interpreter
-
There can be no parameters in the flask view, unlike Django which requires a request
-
When Django returns, there must be an HTTPResponse object or a subclass object (not sure), flask can be returned as a string
-
Flask defaults to port 5000, Django defaults to port 8000
-
The Django configuration template requires the following
-
Check the code first when no results are available
-
run server on http://0.0.0.0:8000
means that this service can be accessed through any ip of this machine plus port 8000. If there are two network cards, access on this machine, through 127, the address of the network card, the network card Both addresses can be accessed
run server on http://127.0.0.1:8000.
If there are two network cards, access on this machine, through 127, the first address of the network card, and the second address of the network card can be accessed.
These two effects Feel the same -