第二章 程序的基本结构
来源:互联网 发布:软件用户体验问卷 编辑:程序博客网 时间:2024/06/06 12:32
2.1 初始化
所有Flask程序都必须创建一个程序实例。
Web服务器使用一种名为Web服务器网关接口(Web Server Gateway Interface,WSGI)的协议,把接收自客户端的所有请求都转交给这个对象处理。程序实例是Flask类的对象,经常使用下述代码创建:
from flask import Flaskapp = Flask(__name__)
Flask类的构造函数只有一个必须指定的参数,即程序主模块或包的名字。在大多数程序中,Python的name变量就是所需的值。
2.2 路由和视图函数
处理URL和函数之间关系的程序称为路由。在Flask中,使用程序实例提供的app.route修饰器,把修饰的函数注册为路由。如:
@app.route('/') #用app.route修饰器定义路由def index(): return '<h1>Hello World!</h1>'
如上代码即把网站的根目录(用/表示)和index()函数绑定在一起,即访问网站首页时,会获得函数index()返回的内容。这里的index()被称为视图函数
动态URL
动态URL可以根据URL中参数的不同而返回不同的页面内容。在Flask中可以通过修饰器实现这一功能:
@app.route('/user/<name>')def user(name): return '<h1>Hello, %s!</h1>' % name
尖括号中的内容就是动态部分。调用视图函数时,Flask会将动态部分作为参数传入函数。 路由中的动态部分默认使用字符串,不过也可以使用类型定义。
eg- 路由/user/只会匹配动态片段id为整数的URL。
Flask支持在路由中使用int、float、path类型,path类型也是字符串,但不把斜线视为分隔符,而将其当作动态片段的一部分。
2.3 启动服务器
程序实例用run方法来启动Flask中集成的Web服务器:
if __name__ == '__main__': '''当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行''' app.run(debug=True)
在run函数中设置debug=True可以启用调试模式,在服务器启动后,会进入轮询,直到程度停止。
2.4 一个完整的程序
from flask import Flaskapp = Flask(__name__)@app.route('/')def index(): return '<h1>Hello World!</h1>'if __name__ == '__main__': app.run(debug=True)
然后使用下述命令启动程序:
(venv) $ python hello.py * Running on http://127.0.0.1:5000/ * Restarting with reloader
访问 http://127.0.0.1:5000/
使用Flask-Script支持命令行选项
使用Flask-Script扩展后,可以通过命令行参数的形式将参数传递给Flask的开发Web服务器 可通过以下命令安装该扩展:
(venv) $ pip install flask-script
Flask-Script扩展的使用示例
from flask import Flask from flask import make_response from flask.ext.script import Manager app = Flask(__name__) manager = Manager(app) @app.route('/') def index(): return '<h1>Hello World!</h1>' @app.route('/user/<name>') def user(name): return '<h1>Hello, %s!</h1>' % name @app.route('/response') def response(): response = make_response('<h1>This document carries a cookie!</h1>') response.set_cookie('answer', '42') return response if __name__ == '__main__': manager.run()
此时,执行python hello.py可得到一个使用提示。主要使用方法有两个:runserver和shell,前者用于启动Web服务器,后者用于启动python shell用于维护任务和调试。可分别通过以下命令执行:
python hello.py runserverpython hello.py shell
运行python python hello.py runserver --help
可获得更多帮助信息
- 第二章 程序的基本结构
- 第二章:WDM驱动程序的基本结构
- 第二章 Java的基本程序设计结构
- 程序的基本结构
- 程序的基本结构
- 程序的基本结构
- COBOL程序的基本结构
- Windows程序的基本结构
- jsp程序的基本结构
- WML程序的基本结构
- VHDL程序的基本结构
- wml程序的基本结构
- JAVA程序的基本结构
- Windows程序的基本结构
- C#程序的基本结构
- C程序的基本结构
- UI_程序的基本结构
- C程序的基本结构
- 打印杨辉三角(非直角三角形打印)
- springmvc 之HandlerExceptionResolver
- 安卓开发之Button
- ceph系列--iscsi配置总结
- 作业作业
- 第二章 程序的基本结构
- Spring AOP的使用
- [练习]Hello World
- linux命令
- 关于rollup的简单用法和层次查询
- setNeedsLayout 和 layoutIfNeeded
- Linux系统的IP配置
- 【Python-3.5】matplotlib绘制气温折线图
- Java day7