2.3:一个最根本应用
Flask框架也是根据膳绫擎的规范实现的web框架,我们可以看下flask源码中对于上述的封装,不过它做了更高层次的抽象
可以看到flask源码中应用wsgi_app和魔术办法__call__对 上述start_respones做了封装。
接下里用flask运行一个hello wordl
2.4:一个最根本应用分析
- /usr/bin/env python
- from Flask import flask
- app = Flask(__name__)
- @app.route('/')
- def index():
- return ‘<h1>Hello World!</h1>‘
- if __name__ == '__main__':
- app.run()
- python hello.py
2.5:最根本应用
app = Flask(__name__) 代码应用Flask类生成一个应用实例
- @app.route('/')
- def index():
- return ‘<h1>hello world</h1>’
一个http过程中请求来自客户端,http办事器(nginx,Apache)再次将请求转发给flask应用实例app,@app.route(‘/)中映射了url链接与一个python函数的对应关系,我们将index函数称之为视图函数。
比如拜访192.168.1.19
---》app.route(‘/’)
拜访192.168.1.19/blog
---》app.route(‘/blog’)
wsgiref包是实现了wsgi标准的一个参考,我们可以用它来进行调试,此包一般用于测试情况,不建议临盆情况中应用。
2.6:可变url
在一般营业中,url都是动态可变的,在flask中我们如许设置可变url
- @app.route(‘/hello/<name>’)
- def hello(name):
- return ‘<h1>hello {}’.format(name)
示例:
拜访192.168.1.19/hello/jack
拜访192.168.1.19/hello/rose
<name> 被尖括号抱起来的部分代表url中与python处理函数中对应的可变部分.
<string:name>、<int:uid>、<path:prefix>
2.7:可变url自定义装换器
常用的有以下3种,定义可变的类型
定义可变url,除了上述的string之外,还有以下几种int、float、path这三种,别的flask还可以经由过程werkzeug中的BaseConverter类,自定义转换器。
这里自定义一个转换器
- fromwerkzeug.routing import BaseConverter
- classListConverter(BaseConverter):
- def to_python(self, value):
- return value.split('+')
- def to_url(self, values):
推荐阅读
沙龙晃荡 | 去哪儿、陌陌、ThoughtWorks在主动化运维中的实践!10.28不见不散! Linux 基金会和在线求职雇用网站 Dice 宣布了一份关于开源雇用的查询拜访结不雅。结不雅显示,相对于其他类>>>详细阅读
地址:http://www.17bianji.com/lsqh/38170.html
1/2 1