Web site backend _python+flask.0012.flask domain name and dynamic sub-domain name implementation?

Source: Internet
Author: User
Tags subdomain

Domain settings:

Description: The setting of the server_name built-in property affects the global URL, which has two main functions, the first of which is to generate an absolute URL outside of the request context, if the setting also affects the absolute URL within the request context, and the second function is for subdomain support

#!/usr/bin/env python# -*- coding: utf-8 -*-"" "## authors: limanman#  51ctobg: http://xmdevops.blog.51cto.com/# purpose:# "" "#  Description:  Import public module from flask  import flask, url_for#  Description:  Import other modules App = flask (__name__) # app.url_map.default _subdomain= ' www ' # app.config.update (server_name= ' blog.51cto.com ') With app.test_request_context ():     print  ' Found notice: with request context full url  is: %s '  %  (        url_for (' Static ',  Filename= ' Css/style.css ',  _external=true),    ) With app.app_context ():     print  ' Found notice: with app context full url is:  %s '  %  (        url_for (' Static ',  filename= ' css/ Style.css ',  _external=true),    ) if __name__ ==  ' __main__ ':     app.run (host= ' 0.0.0.0 ',  port=9000, debug=true)

Note: If the above code is not set server_name default property, the direct run will be reported Runtimeerror:application is not able to the create a URL adapter for request Independent URL generation. You might is able to the fix this by setting the server_name config variable. Description url_for is dependent on the request context, to generate a request context that is not dependent on (that is, in the request context or the program context , the most common is when you send a message asynchronously when you url_for the address in the generated message, you must set the server_name


Subdomain implementations:

Note: server_name is also used for subdomains, because flask can not guess the subdomain part before knowing the existing server name, if server_name is not set in the request context, Request.host is used by default, but once set Server_ Name, which will affect the host portion of the full URL globally, so in order for flask to recognize subdomains with. Segmentation, it is strongly recommended to set server_name as the specified domain name, and the name must be Server_name= 'blog.51cto.com : 9000 ' main domain name plus the form of the port, otherwise it will not take effect, the following is a simple demonstration under the General project development of the use of sub-domain name and isolation of resource files and template method, because the code is a bit more, directly upload code to explain

: http://1000eb.com/1kw8v

. │main.py│├─app││prod_config.py││test_config.py││__init__.py│││├─monitor│││api.py│││views.py │││__init__.py│││││├─static│││└─js│││main.js│││││└─templates│├─static│└─temp Lates├─bin└─doc

1. main.py for the portal file, invoke the Create_app function under the app package to create the app instance, and then call App.run to launch the instance

2. Configure the production environment in prod_config.py, and then the local test environment tries to import test_config.py as the current configuration, server_name is declared in test_config.py, and when the production environment is released, remove Test_ Config.py can

3. A monitor blueprint is defined in the monitor package, and the subdomain= ' monitor ' is specified when the blueprint is created, allowing us to access monitor.blog.51cto.com automatically when the monitor blueprint is However, it is important to note that the name of the blueprint is strongly recommended when using url_for () to generate a path in a view function or template, such as url_for ('. Static ', filename= ' js/main.js ', _external=true)/url_for (' Monitor.static ', filename= ' js/main.js ', _external=true) is generated by Http://monitor.blog.51cto.com/static/js/main.js, The corresponding file is the App/monitor/static/js/main.js file, while the url_for (' Static ', filename= ' js/main.js ', _external=true) is generated by/HTTP Blog.51cto.com/static/js/main.js, trying to access the inevitable inaccessible, generally encountered this problem, you can use the Nginx front-end rewrite rewrite the URL plus a default sub-domain, such as www can be resolved

4. The Create_app function primarily loads the configuration in the prod_config.py and registers the monitor blueprint in the monitor package


Through the gamete domain:

Description: Sometimes need a blueprint to match multiple subdomains, such as 51CTO to each registered user to assign a sexual domain name similar to http://xmdevops.blog.51cto.com/, and each user has their own home page, as well as different information display page, you can use the dynamic URL

#!/usr/bin/env python# -*- coding: utf-8 -*-"" "## authors: limanman#  oschina: http://xmdevops.blog.51cto.com/# purpose:# "" "#  Description:  Import public module from flask  import blueprint, g#  Instructions:  Import other modules monitor = blueprint (' Monitor ',  __name__,  subdomain= ' <subdomain> ',                     static_folder= ' Static ',                     template_folder= ' templates ') @monitor. Url_value_preprocessordef set_site (endpoint, values):     g.subdomain  = values.pop (' subdomain ',  none) @monitor. Url_defaultsdef get_site (endpoint, values):     values.update (' subdomain ',  g.subdomain) @monitor. Before_requestdef get_user () :    # g.user = webuser.query.filter_by (Name=g.subdomain). first_or_404 ()      g.user = g.subdomain if g.subdomain else nonefrom . import  Apifrom . import views

Description: In the previous code only this modified the code in app/monitor/__init__.py, when the blueprint was created to modify the parameters subdomain= ' <subdomain> ', is actually using a string converter, We want to enter a different user name subdomain to jump to a different user homepage, such as the above code with the Localthread object G, based on thread-isolated objects, such as when accessing http://user1.blog.51cto.com:9000, because our DNS has done a pan-parsing , pointing to 127.0.0.1 (add simulation directly to the Hosts file), so the value of Request.host is set to user1.blog.51cto.com:9000 because we app.url_map.default_ Subdomain is set to ' blog.51cto.com:9000 ' and the Monitor blueprint is created with subdomain= ' <subdomain> ' that exactly matches the form of the subdomain, Therefore, the value of subdomain is passed to the view function and the internally encoded URL after the converter in the current_app.url_map.converts is converted, respectively. But we want to get subdomain and put it into the Localthread G object for thread isolation access before passing it to the view function, Flask gives us monitor.url_defaults and Monitor.url_value_ Preprocessor two adorners, both call a function to receive endpoint, values, endpoint is actually the blueprint, values store the URL under this blueprint dynamic name and dynamic content mapping relationship (such as subdomain: Subdomain value), Monitor.url_value_preprocessor will send data from subdomain to the G object after the data has been converted, but if you access it directly at this time, the pit will give an error saying that there are fewer parameters, Because you put the subdomain pop up ~, so the role of url_defaults is to wait for the URL processing after the pre-conversion and value processing to re-update the value, and finally in the Monitor.before_request processing request before the sub-domain name for the user object ~ As for the rest of the matter is the rendering page ~


This article is from "@Can up and No BB ..." Blog, be sure to keep this source http://xmdevops.blog.51cto.com/11144840/1866989

Web site backend _python+flask.0012.flask domain name and dynamic sub-domain name implementation?

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.