1283 阅读 · 2020年5月27日 22:47 更新 · 作者:clannadhh
小伙伴们还记得昨天我们写的Flask的Hello,world吗?
什么?昨晚吃鸡打太晚忘记了。
没事没事,我们再来看下代码。

小朋友,你是不是有很多问号?为什么短短几句就能跑一个web服务呢?一方面得益于万能的python,另一方面呢,得益于flask这个优秀的框架。
接下来我们来一步步解剖代码。
from flask import Flask
app = Flask(__name__)
细心的盆友会发现,这里传递了一个参数 __name__ 。我们来看下官方文档怎么说的。
If you are using a single module (as in this example), you should use
__name__because depending on if it’s started as application or imported as module the name will be different ('__main__'versus the actual import name).
意识就是说如果你使用 一个单一模块(就像本例),使用 __name__ 就可以。如果是一个应用程序包,那就硬编码一个名字给它就行。比如这样:
app = Flask("nb")
这个参数是必需的,这样 Flask 才能知道在哪里可以 找到模板和静态文件等东西。由于目前我们的应用都相对简单,所以统一使用__name__作为参数。
然后我们使用 route() 装饰器来告诉 Flask 触发函数的 URL 。当我们用浏览器访问"/"时,flask应用会向浏览器返回"Hello World!"。
@app.route('/')
def hello_world():
return 'Hello World!'
当然我们可以修改成其他的,如下。当我们用浏览器访问"/index"时,flask应用同样会向浏览器返回"Hello World!"。
@app.route('/index')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
而app.run方法中实际上是调用了FLASK的__call__方法,__call__又是调用了 wsgi_app(environ, start_response)。由于涉及源码,这里暂时不展开讨论。