Tutorial on configuring SERVER_NAME domain name items in the Flask framework of Python, flaskserver_name
SERVER_NAME in Flask mainly performs the following two tasks:
- Assists Flask in generating absolute URLs (for example, embedding website URLs in emails) out of the request)
- Used for subdomain support
Many people mistakenly think that it can do anything other than these two things.
1. First thing: absolute URL
We know that url_for generates a relative URL by default, which has a parameter _ external. If it is set to true, an absolute URL (that is, HTTP header with domain name and other information) will be generated ). If SERVER_NAME is not specified, the current active request is used by default to generate a URL.
The following is an example:
# filename myapp.pyfrom flask import Flask, url_forapp = Flask(__name__)@app.route('/')def index(): return 'hello flask'@app.route('/test')def test(): return url_for('index', _external=True)if __name__ == '__main__': app.run(debug=True)
1. [scenario 1] access through a browser
After the app runs, it listens on the local port 5000.
(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 a browser, the returned content is: http: // 127.0.0.1: 5000 /.
If we access http: // localhost: 5000/test through a browser, the returned content is: http: // localhost: 5000 /.
We can see that the absolute URL generated by url_for depends on the requested URL without setting SERVER_NAME. Next, let's take a look at the situation that is not accessed through a browser.
2. [scenario 2] non-browser access
This scenario indicates that the request does not exist.
We use Python Shell to simulate:
>>> from myapp import app>>> with app.app_context():... print url_for('index', _external=True)...
Traceback (most recent call last): File "<stdin>", line 2, in <module> File "F:\tmp\env\lib\site-packages\flask\helpers.py", line 287, in url_for raise RuntimeError('Application was not able to create a URL 'RuntimeError: Application was not able to create a URL adapter for request independent URL generation. You might be able to fix this by setting the SERVER_NAMEconfig variable.
The above means that the application cannot create a URL adapter for URL generation that is not related to the request. You can set SERVER_NAME to solve this problem.
Well, 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: Generally, SERVER_NAME is set to the domain name of the website.
In articles related to Flask-Mail:
Many Flask extensions assume that they are running in an active application and request context. The Flask-Mail send function uses the current_app context, so when mail. when the send () function is executed in a thread, a context needs to be created manually. All applications are used in send_async_email. app_context () to create a context.
Therefore, to generate an absolute URL that does not depend on the request (for example, the URL of a website page is generated in the mail when an asynchronous mail is sent), you must set SERVER_NAME.
2. Second thing: subdomain name support
The SERVER_NAME key is used for subdomain support. Because Flask cannot guess the subdomain before learning the existing server name, if you want to use the subdomain name, this option is necessary and also used for session cookies.
Remember that not only does Flask have the problem of not knowing the subdomain name, but also does exist in your browser. Most modern web Browsers Do Not Allow Server names to contain cross-subdomain cookies. Therefore, if your server is named localhost, you cannot set a cookie for localhost and all its subdomain names. Select a proper server name, such as 'myapplication. local', and add the desired server name + sub-domain name to your host to configure or set a local bind.
Examples
-------->http://book.muxistudio.com ||http://muxistudio.com-------->http://blog.muxistudio.com || -------->http://share.muxistudio.com
1. Local Test
Modify the/etc/hosts file
Note: It is valid only for local tests!
Add all the subdomains to be used, for example:
127.0.0.1 flask. dev localhost # domain name 127.0.0.1 test. flask. dev localhost # subdomain name 127.0.0.1 othertest. flask. dev localhost # subdomain name
Add 'server _ name' to the configuration file of the Flask application'
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. Configure the blueprint
The subdomain in the blueprint is the subdomain name added in the hosts file.
#...# Blueprint declarationbp = Blueprint('subdomain', __name__, subdomain="<user>")#...# Register the blueprint into the applicationapp.register_blueprint(bp)#...
3. Server Configuration
Change 'server _ name' in the Flask application settings to the domain NAME registered in the production environment
flask.dev:5000 ----> muxistudio.com
4. Nginx Configuration
Configure the listening port. In the following example, the regular expression is used to obtain the subdomain name accessed by the user. for www, it should be filtered when the regular expression is obtained, redirect a user to www.yourdomain.com during access. Otherwise, www will be treated as a subdomain name.
Configuration instance:
server { listen 80; 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 301 "$scheme://${user}markdownblog.com$request_uri"; } server { listen 80; 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; }}