I love the Debug mode configuration of the Flask framework

The yellow part is highlighted

1. Debug mode settings

       • Flask library by defaultWill not open DEBUG mode, After opening the DEBUG mode, flask will save the code every timeAutomatically reload code, And if there is an error in the code, it will prompt in the terminal.

Run the test:

       • first_flask()Add an error code to the function for testing:

from flask import Flask

app = Flask(__name__)


# 装饰器,将当前路由映射到对应函数
@app.route('/')
def first_flask():
    result = 1 / 0 # 出现错误
    return 'Hello Flask'


if __name__ == '__main__':
    app.run()

       •runOpen serviceAfter that, you will find in the browser:
Insert picture description here
       •Compiler logYou will also find the following error:

[2020-10-15 13:14:29,845] ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "D:\envs\Flaskframe-UbajLYNV\lib\site-packages\flask\app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\envs\Flaskframe-UbajLYNV\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\envs\Flaskframe-UbajLYNV\lib\site-packages\flask\app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\envs\Flaskframe-UbajLYNV\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "D:\envs\Flaskframe-UbajLYNV\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\envs\Flaskframe-UbajLYNV\lib\site-packages\flask\app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:/Flaskframe/第一讲/first_flask.py", line 9, in first_flask
    result = 1 / 0
ZeroDivisionError: division by zero
127.0.0.1 - - [15/Oct/2020 13:14:29] "GET / HTTP/1.1" 500 -

       • ThisOperation modeObviouslytrouble, And after each modificationMust rerun, And the error message can only be inLogSeen in.
       • At this time we needTurn on Debug mode, So every timeModify the codeRearSave code will re-run, And there will be problems with the codeShow error message

Note: After modifying the code, you must save it before you can run it again. Most compilers use (Crtl+S) to save the code shortcut

Several ways to open Debug:

       • run()Set in the methodThe debug parameter is True:

if __name__ == '__main__':
    app.run(debug=True) #debug参数为True

       • Set the debug property of the app object instance to True:

if __name__ == '__main__':
    app.debug = True #实例的debug属性为True
    app.run()

       • Through the attribute setting of the configuration parameter config:

if __name__ == '__main__':
    app.config.update(DEBUG=True)
    app.run()

       • It configis inherited from the dictionary type, you can use the dictionary type update()method.
Turn on the Debug mode to test as follows:

from flask import Flask

app = Flask(__name__)


# 装饰器,将当前路由映射到指定函数
@app.route('/')
def first_flask():
    result = 1 / 0
    return 'Hello Flask'


if __name__ == '__main__':
    app.run(debug=True)

       • Save and run, view the web page:
Insert picture description here
       •ConsoleWill also promptTurn on Debug mode

 * Serving Flask app "first_flask" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on  # on表示Debug模式已开启
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 338-200-360
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

       •whenDebug mode onRear,Modify the code and save, WillAutoloadThe code restarts the service, no moreManual shutdownThe service restarted again.

2. Configuration and configuration files

       • The various configurations of the Flask project are passedapp.config objectTo configure it.
       • If you want to configure a Flask project to run in Debug mode, you can useapp.config[‘DEBUG’] = TrueTo set up the Flask project to run in Debug mode.

Several different methods of project configuration:

   1. Direct hard coding
硬编码的方式不灵活,不便于进行复用(多次使用)。

app = Flask(__name__)
app.config['DEBUG'] = True

   2. Through the dictionary update() method
       •Because app.config is flask.config.ConfigInstance, And the Config class isInherited from dictionary type, So it can update()方法be configured through .

app.config.update(
   DEBUG=True,
   SECRET_KEY='...'
)

   3. Through the module from_object() method
       •When neededVery many configuration itemsTime, you can put all the required configuration items in oneModuleIn, then passLoad moduleWay to configure.
       • Suppose there is a settings.py module dedicated toStorage configuration itemsYes, at this time you can app.config.from_object()方法load the configuration items by performing, and this method canThe string name of the receiving module,can also beModule object

Load configuration items in two different forms:
# 1. 通过模块字符串
app.config.from_object('settings')
# 2. 通过模块对象
import settings
app.config.from_object(settings)

       • After adding a configuration file, put the configuration items in this file, and other files directly refer to the configuration items in the configuration file, which improves the reusability of the code and reduces the coupling. At the same time, when a configuration item is modified in the configuration file, no modification is required in other codes, which greatly improves the flexibility of the code.

Add the Debug mode configuration to the configuration file:

       • Create a new config.py file and add configuration items as follows:

# 设置Debug模式为True,开启Debug模式
DEBUG = True

# 指定HOST
HOST = '127.0.0.1'

       • Import the configuration file in the required file:

from flask import Flask
import config

app = Flask(__name__)


# 装饰器,将当前路由映射到指定函数
@app.route('/')
def first_flask():
    result = 1 / 0
    return 'Hello Flask'


if __name__ == '__main__':
    app.config.from_object(config)
    app.run()

       • Run again to start the Debug mode.
   Can also be imported as a string

if __name__ == '__main__':
    app.config.from_object('config')
    app.run()

   4. By from_pyfile () method
       • app.config.from_pyfile()方法pass a filename, usually ending with .py file, also can use other file suffix.
       • Import configuration files by importing Python files:

if __name__ == '__main__':
    app.config.from_pyfile('config.py')
    app.run()

       • from_pyfile()方法one ofsilent parameter,Set asTrueWhen the configuration file does not exist, it will notAn error occurred;
       •It not only supports configuration files in Python format, but also supports configuration files in other formats such as .ini.

If you have any questions, you can correct me in the comments, welcome to discuss, thank you! !

Guess you like

Origin blog.csdn.net/qq_45261963/article/details/109095209