Flask的SERVER_NAME解析 - digwtx's Blog

Flask的SERVER_NAME解析

digwtx posted @ 2014年12月05日 11:40 in Python with tags python flask , 3084 阅读

SERVER_NAME是Flask中比较容易用错的一个设置值,本文将介绍如何正确使用SERVER_NAME

Flask中的SERVER_NAME主要做两件事:

  1. 协助Flask在活动的请求(request)之外生成绝对URL(比如邮件中嵌入网站URL)
  2. 用于子域名支持

很多人误以为它可以做这两件事之外的其它事情。

第一件事:绝对URL

我们知道,url_for默认情况下是生成相对URL,它有个参数_external,如果设置为真,则会生成一个绝对URL(就是HTTP开头带域名等信息的)。若不指定SERVER_NAME,默认使用当前活动的请求(request)来生成URL。

下面举个例子演示一下:

# filename myapp.py
from flask import Flask, url_for

app = 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】通过浏览器访问

app运行之后,在本地5000端口监听。

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

若我们通过浏览器访问http://127.0.0.1:5000/test,则返回的内容是:http://127.0.0.1:5000/

若我们通过浏览器访问http://localhost:5000/test,则返回的内容是:http://localhost:5000/

可以看出,在未设置SERVER_NAME的情况下,url_for生成的绝对URL是依赖于请求的URL的。下面我们来看看不通过浏览器访问的情况。

【情景2】非浏览器访问

这个情景是指不存在request请求的情况。

我们通过Python Shell来模拟:

>>> 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 indep
endent URL generation. You might be able to fix this by setting the SERVER_NAME
config variable.

上面的意思是说应用程序不能创建一个用于与request不相关的URL生成的URL适配器,可以通过设置SERVER_NAME来解决这个问题。

好,下面我们为SERVER_NAME设置一个值之后再试试:

>>> app.config['SERVER_NAME'] = 'example.com'
>>> with app.app_context():
...     print url_for('index', _external=True)
...
http://example.com/

PS: 一般SERVER_NAME设置为网站的域名。

Flask-Mail相关的文章中有这么一段话:

许多Flask的扩展都是假定自己运行在一个活动的应用和请求上下文中,Flask-Mail
send函数使用到current_app这个上下文了,所以当mail.send()函数在一个
线程中执行的时候需要人为的创建一个上下文,所有在send_async_email中使用了
app.app_context()来创建一个上下文。

原文如下:

Many Flask extensions operate under the assumption that there are active
application and request contexts. Flask-Mail's send() function uses
current_app, so it requires the application context to be active. But
when the mail.send() function executes in a different thread, the
application context needs to be created artificially using
app.app_context().

因此,若要生成不依赖于request的绝对URL(比如异步发送邮件时在邮件中生成网站某个页面的URL),就必须要设置SERVER_NAME

第二件事:子域名支持

SERVER_NAME键是用于子域名支持。因为 Flask 在得知现有服务器名之前不能猜测出子域名部分,所以如果你想使用子域名,这个选项必要的,并且也用于会话cookie。

请牢记不只有 Flask 存在不知道子域名的问题,你的浏览器同样存在这样的问题。 大多数现代 web 浏览器不允许服务器名不含有点的跨子域名 cookie。因此如果你的服务器的 名称为 localhost,你将不能为 localhost 和所有它的子域名设置一个 cookie。 请选择一个合适的服务器名,像 'myapplication.local', 并添加你想要的服务器名 + 子域名 到你的 host 配置或设置一个本地 bind。

对于子域名部分,会有另外一篇文章详细说明。

原文:http://flask123.sinaapp.com/article/44/

Avatar_small
tham 说:
2014年12月08日 21:33

很好的个人网站,内容非常充实,全是干货。可是博主为什么在平常写博文的时候,不对文章进行归类处理呢?这样应该管理和阅读更方便啊!

Avatar_small
setup dual monitor 说:
2019年6月21日 14:49

This is very good, so to set all commands to monitor for windows 10, I am here to share all the updates to fix all the settings and bring changes to the monitor screen

Avatar_small
ssali 说:
2022年5月22日 19:41

Great stuff. i am going to bookmark it, if you are looking for lyca beltegoed, lebara beltegoed, lyca bundel xs, samsung a52, samsung a51, samsung a72, iphone 13 pro max in Netherlands, get in touch with us.

 

Avatar_small
what is DNS 说:
2022年8月10日 19:05

DNS Port which is abbreviated as Domain Name System is used to configure and sync the Domain name from a Domain service provide to an IP Address of a hosting. In order for a website to be hosted on the Internet and to function smoothly, there should be fixed DNS and it translates the required information to the hosting, so the worldwide web can access the service as well. what is DNS In simple terms, we can consider a Domain name and let us take the example of Google.com and here the Google.com is called the website full name, where the Google is only the partial domain name representing the main keyword.

Avatar_small
HBSE Model Paper Cla 说:
2022年9月03日 18:20

Haryana Board Model Paper 2023 Class 6 Pdf Download with Answers for English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. HBSE Model Paper Class 6 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.

Avatar_small
heardle game 说:
2022年9月11日 13:14

Hello and welcome to Heardle Game, a daily music-based brain exercise game. With just a few notes of the music, the player's primary objective is to identify the song's title and artist. Nowadays, people frequently use their laptops or mobile devices to play games to decompress. Everyone will enjoy playing games that can entertain, relax, and train the brain.

Avatar_small
the backrooms 说:
2022年10月16日 15:09

You can explore a variety of environments, hallways, levels, and pretty much everything else you can think of in the survival horror game The Backrooms

Avatar_small
tunnel rush 说:
2022年11月03日 11:42

It is necessary to have a permanent DNS in place for a website in order for it to be hosted on the internet and to operate without any hiccups. The DNS translates the necessary information to the hosting, making it possible for the whole world wide web to access the service.

Avatar_small
Alyssa 说:
2023年1月07日 20:29

Flask's SERVER_NAME resolution is a bit different than what you might be used to. By default, Flask will take the server name from the request headers, but you can also diamond rings explicitly set the server name in the Flask config. This can be useful if you want to run your app on a different server than the one specified in the request headers.

Avatar_small
안전놀이터 说:
2023年1月08日 21:22

Hi my family member! I want to say that this post is awesome, great written and include almost all significant infos. I’d like to peer more posts like this .

Avatar_small
Mario Games 说:
2023年5月19日 16:37

This post is fantastic; it's very well written and covers practically all the relevant points.

Avatar_small
terapia de pareja 说:
2023年6月25日 22:55

En el ámbito de la terapia psicológica de pareja, así como en el tratamiento individual, también existe la opción de solicitar una terapia de manera online, modalidad que presenta ciertas ventajas que deben ser tenidas en cuenta. Algunas de estas son la mayor flexibilidad de horarios y comodidad, mayor seguridad y anonimato en el paciente a quien le cueste desplazarse hacia una consulta psicológica y casi siempre, un coste de terapia más económico.

Avatar_small
drift boss 说:
2023年7月19日 17:54

Greetings, beloved! This post is fantastic; it's very well written and covers practically all the relevant points. Please make such posts in the future.

Avatar_small
geometry dash scratc 说:
2023年9月14日 15:45

Algunas de estas son la mayor flexibilidad de horarios y comodidad, mayor seguridad y anonimato en el paciente a quien le cueste desplazarse

Avatar_small
SEO 说:
2023年12月03日 21:18

No more worries about scams with 메이저사이트. Toto Match's strict scam verification guarantees a fraud-free betting experience.

Avatar_small
civaget 说:
2023年12月04日 01:18

백링크 is the backbone of SEO. A well-crafted strategy can significantly boost your website's visibility, drive traffic, and enhance your online authority. Dive into the world of 백링크 and watch your SEO soar!

Avatar_small
civaget 说:
2023年12月16日 15:03

해외축구중계 brings global soccer to my screen. It's a world of matches, goals, and excitement.

Avatar_small
civaget 说:
2023年12月17日 18:36

op사이트 순위 rankings are your source of trusted information.

Avatar_small
civaget 说:
2023年12月18日 23:26

I rely on 오피가이드 for my officetel escapades.

Avatar_small
civaget 说:
2023年12月20日 03:41

오피타임's user-friendly interface simplifies finding the perfect service.

Avatar_small
civaget 说:
2023年12月20日 22:35

오피가이드 is where business enthusiasts thrive. The diverse range of topics keeps users engaged and informed.

Avatar_small
civaget 说:
2023年12月27日 19:36

The 부달 app's location-based features are a traveler's dream.

Avatar_small
civaget 说:
2024年1月04日 22:50

오피스타 is a game-changer for locating nearby massage parlors. Highly recommended!

Avatar_small
civaget 说:
2024年1月08日 21:05

오피매거진' is my urban oasis for healing and tranquility.

Avatar_small
civaget 说:
2024年1月10日 22:26

누누티비 최신 has content for everyone in the family, making it our go-to platform.

Avatar_small
seo service london 说:
2024年1月13日 22:09

i am for the first time here. I found this board and I in finding It truly helpful & it helped me out a lot. I hope to present something back and help others such as you helped me.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter
Host by is-Programmer.com | Power by Chito 1.3.3 beta | © 2007 LinuxGem | Design by Matthew "Agent Spork" McGee