Instantiate the parameters of the flask and configure the app

Source: Internet
Author: User

Flask is a very flexible and short-witted web framework, so where does flexibility manifest itself?

There is a magical thing called flask configuration, how to use this thing? What kind of convenience can it bring us?

First show:

From flask Import Flaskapp = Flask (__name__)  # type:flaskapp.config["DEBUG"] = True

This sentence app.config["DEBUG"] = True can be achieved by the function can stimulate the

Automatically restarts the Flask program (App.run) as soon as the code changes

The information printed on the console is very comprehensive

The above two functions are the legendary debug mode (debug mode)

Flask's configuration is to add a key-value pair in app. Config, but the key you put in must be in config, and if it doesn't, it will be useless by default.

How many useful keys are there in config?

{' Debug ': false, # Whether to turn on DEBUG mode ' testing ': false, # Whether to turn on test mode ' propagate_exceptions ': None, # Exception propagation (whether to print log in console) When debug or testing is turned on, auto is true ' preserve_context_on_exception ': None, # One or two words are not clear, generally do not use it ' secret_key ': None, # Encountered before, in the Kai Use the session, must have it ' permanent_session_lifetime ': ~, # days, SESSION life cycle (day) default 31 days ' Use_x_sendfile ': False, # is deprecated    X_sendfile ' Logger_name ': None, # logger name ' Logger_handler_policy ': ' Always ', ' server_name ': None, # service access domain name ' Application_root ': None, # The full path of the project ' Session_cookie_name ': ' Session ', # Storing the name of the session encrypted string in the cookie ' Session_cookie  _domain ': None, # under which domain name will generate SESSION record in cookies ' Session_cookie_path ': None, # cookies path ' session_cookie_httponly ': True, # Controls whether the cookie should be set HttpOnly flag, ' session_cookie_secure ': False, # Controls whether the cookie should be set to the security flag ' Session_refresh_ea Ch_request ': True, # This flag controls how a permanent session refreshes ' max_content_length ': None, # If set to bytes, Flask rejects a request entry with a content length greater than this value and returns a 413 status code ' Send_file_max_age_defaulT ': # hours Default cache control maximum age ' trap_bad_request_errors ': False, # If this value is set to True, flask does not perform error handling of HTTP exceptions, but as with other exceptions, # Let it bubble up through the exception stack.    This is useful for scary debugging scenarios that need to find the source of the HTTP exception.    ' Trap_http_exceptions ': False, # Werkzeug The internal data structure that handles the specific data in the request throws a special key errors that is also the "wrong request" exception.    Similarly, in order to remain consistent, many operations can explicitly throw badrequest exceptions.    # Because in debugging, you want to pinpoint the cause of the exception, this setting is used to debug in these situations.    # If this value is set to True, you will only get regular backtracking.  ' explain_template_loading ': False, ' preferred_url_scheme ': ' http ', # when generating the URL if no URL pattern is available, this value ' Json_as_ascii ' will be used: True, # Flask uses ASCII encoding to serialize the object by default.    If this value is set to False, # Flask does not encode it as ASCII and outputs it as-is, returning its Unicode string.    # For example, Jsonfiy will automatically use Utf-8 to encode it before transmitting.    ' Json_sort_keys ': True, #默认情况下 Flask serializes it in the order of the keys of the JSON object.    # This is done to ensure that the order of the keys is not affected by the hash seed of the dictionary, so that the returned values are consistent every time and do not cause unnecessary additional HTTP caches. # You can override the default action by modifying the value of this configuration.    But this is not recommended because this default behavior may give you an improvement in the cost of performance. ' Jsonify_prettyprint_regular ': True, ' jsonify_mimetype ': ' Application/json ', ' templates_auto_reload ': None,}

These keys can be rewritten, of course, they also have default values exist, if there is no special case, do not overwrite its default value

The configuration is modified in approximately two ways

1. Modify the app. config directly

app.config["DEBUG"] = True

2. Importing by using a class

First you have to have a settings.py file.

Class Flasksetting:    DEBUG = True    secret_key = "Dragonfire"

And then we can write that in flask's boot file.

From flask Import Flaskapp = Flask (__name__)  # type:Flaskapp.config.from_object ("Settings. Flasksetting ")

This is called Class import configuration

This is a configuration for an already instantiated app

So when the flask instantiation, what are the arguments passed?

In fact, it can be understood as the initial configuration of the flask instance, which is a very good understanding of the parameters, note that the keyword is very very very good understanding

Static_folder = ' static ',  # The path to the static file directory defaults to the static directory in the current project Static_host = None,  # The host address used by the remote static file, the default is empty Static_url_ Path = None,  # The URL path of the static file directory is not written by default is the same name as Static_folder, the remote static file is reused # host_matching whether to turn on host host bit matching, is to use with Static_host, If Static_host is configured, you must assign a value of true# here to illustrate, @app. Route ("/", host= "localhost:5000") must be written like this # host= "localhost:5000" if the host header is not LOCALHOST:5000 is unable to pass the current route host_matching = False,  # If not specifically required, use caution, otherwise all routes need to host= "" Parameter subdomain_matching = False,  # is theoretically used to restrict server_name subdomains, but there is no sense of the difference where Template_folder = ' templates '  # template directory, default current project Templates directory Instance_path = None,  # Path to another flask instance instance_relative_config = False  # Whether to load the configuration of another instance Root_path = None  # Absolute path to the directory where the main module resides, default project directory

In this, the parameters we use are

Static_folder = ' static ',  # The path to the static file directory is default to the static directory in the current project Static_url_path = None,  # The URL path of the static file directory is not written by default is with Static_ Folder with the same name, the remote static file is reused Template_folder = ' templates '  # template directory, default current project templates directory

Just remember that. In a general project, only these parameters are modified

Instantiate the parameters of the flask and configure the app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.