The configuration tutorials for server_name domain names in the Python flask framework _ruby topics

Source: Internet
Author: User
Tags sub domain subdomain

The server_name in flask mainly do two things:

    • Assists flask to generate an absolute URL outside of an active request (request) (such as embedding a site URL in a message)
    • For child domain name support

Many people mistakenly think that it can do anything other than these two things.

One, the first thing: absolute URL
we know that url_for by default generates a relative URL, it has a parameter _external, and if set to True, an absolute URL is generated (that is, HTTP starts with a domain name, and so on). If you do not specify a server_name, the URL is generated by default using the currently active requests (request).

Here's an example to illustrate:

# filename myapp.py
from flask import flask, url_for

app = Flask (__name__)

@app. Route ('/')
def index (): Return to
 ' Hello Flask '

@app. Route ('/test ')
def Test (): Return
 url_for (' index ', _external=true)

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

1. "Scenario 1" accessed through the browser

After the app runs, it listens on the local 5000 port.

(ENV) F:\tmp>python myapp.py
 * Running on http://127.0.0.1:5000/
 * Restarting with Reloader

If we access http://127.0.0.1:5000/test through the browser, the returned content is: Http://127.0.0.1:5000/.

If we access http://localhost:5000/test through the browser, the returned content is: Http://localhost:5000/.

As you can see, when server_name is not set, the absolute URL generated by url_for is dependent on the requested URL. Let's look at the situation that is not accessed through the browser.

2. "Scenario 2" non-browser access

This scenario refers to a situation where request requests do not exist.

We simulate this through the Python shell:

>>> from MyApp import app
>>> with App.app_context ():
... print url_for (' index ', _external= True)
...
Traceback (most recent):
 File "<stdin>", line 2, in <module>
 File "F:\tmp\env\lib\ site-packages\flask\helpers.py ", line 287, in Url_for
 raise RuntimeError (' application is not able to create a URL ' 
   runtimeerror:application is not able to create a URL adapter the for request INDEP
endent URL generation. You are able to fix this by setting the server_name
config variable. \ might

The above means that the application cannot create a URL adapter that is generated for URLs that are not related to the request, and can resolve the problem by setting server_name.

OK, now let's set a value for server_name and try again:

>>> app.config[' server_name '] = ' example.com '
>>> with App.app_context ():
. Print Url_ For (' index ', _external=true)
...
http://example.com/

PS: General server_name is set to the domain name of the Web site.

There is this passage in the Flask-mail-related article:

Many flask extensions are assumed to run in an active application and request context, and the Flask-mail send function uses the context of Current_app, so when Mail.send () When a function executes in a thread, it needs to create a context artificially, all using App.app_context () in Send_async_email to create a context.

Therefore, to generate an absolute URL that does not depend on request, such as generating a URL for a page in a Web site in a message when the message is sent asynchronously, you must set up server_name.

Two, the second thing: sub-domain support
the server_name key is for child domain name support. Because flask cannot guess the subdomain part until you know the existing server name, if you want to use a subdomain, this option is necessary and is also used for session cookies.

Keep in mind that not only does flask exist without knowing the subdomain, your browser also has this problem. Most modern web browsers do not allow the server name to contain a bit of cross subdomain cookies. So if your server's name is localhost, you will not be able to set a cookie for localhost and all of its sub domains. Please select a suitable server name, like ' myapplication.local ', and add the server name you want + subdomain to your host configuration or set up a local bind.
Examples

   -------->http://book.muxistudio.com
   | |
http://muxistudio.com-------->http://blog.muxistudio.com
   | |
   -------->http://share.muxistudio.com

1. Local test

modifying/etc/hosts files

Note: Valid only in local tests!

Add all the subdomains you want to use, for example:

127.0.0.1 flask.dev  localhost # domain
127.0.0.1 test.flask.dev localhost # sub domain name
127.0.0.1 othertest.flask.dev LocalHost # sub domain name

Add ' server_name ' to the Flask application's configuration file

In the application configuration, set ' server_name ' to the specified domain name and the default listening port, for example:

#...
App = Flask (__name__)
app.config[' server_name ' = ' flask.dev:5000 '
# ...

2. Configuration Blueprint

Subdomain in the blueprint for the subdomains added in the Hosts file

#...
# Blueprint declaration
bp = Blueprint (' subdomain ', __name__, subdomain= "<user>")

#

# Register The blueprint into the application
App.register_blueprint (BP)
# ...

3. Server-side configuration

Speak flask ' server_name ' in application settings modify the domain name registered in the production environment

flask.dev:5000----> muxistudio.com

4.Nginx Configuration

Configure the listening port, the following example uses a regular expression to obtain the user access to the subdomain, for WWW, should be when the regular expression is obtained to filter it, when the user access to redirect it to the www.yourdomain.com page, otherwise www will be considered as a subdomain.

Configuration instance:

 server {
 listen;
 Listen 443 SSL;

 SSL_CERTIFICATE/USR/LOCAL/NGINX/SSL/NGINX.CRT;
 Ssl_certificate_key/usr/local/nginx/ssl/nginx.key;

 server_name ~^www\. (<user>.+\.)? markdownblog\.com$;
 Return "$scheme://${user}markdownblog.com$request_uri";
 }

 server {
 listen;
 Listen 443 SSL;

 SSL_CERTIFICATE/USR/LOCAL/NGINX/SSL/NGINX.CRT;
 Ssl_certificate_key/usr/local/nginx/ssl/nginx.key;

 server_name ~^.+\.markdownblog\.com$ markdownblog.com;

 Location/{
  proxy_set_header Host $http _host;
  Proxy_set_header x-real-ip $remote _addr;
  Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
  Proxy_pass http://127.0.0.1:8085
 }
}

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.