1、flask入门与路由
2、flask路由
3、flask请求响应异常
Flask是一个基于Python实现的web开发的'微'框架html
中文文档地址前端
Flask和Django同样,也是一个基于MVC设计模式的Web框架python
flask流行的主要缘由:web
a)有很是齐全的官方文档,上手很是方便 b) 有很是好的拓展机制和第三方的拓展环境,工做中常见的软件都有对应的拓展,本身动手实现拓展也很容易 c) 微型框架的形式给了开发者更大的选择空间
virtualenv --no-site-packages falskenv 激活windows下虚拟环境 cd Scripts activate
pip install flask
建立hello.py文件flask
from flask import Flask app = Flask(__name__) @app.route('/') def gello_world(): return 'Hello World' if __name__ == '__main__': app.run()
运行:python hello.pywindows
from flask import Flask app = Flask(__name__)
Flask类构造函数惟一须要的参数就是应用程序的主模块或包。对于大多数应用程序,Python的__name__变量就是那个正确的、你须要传递的值。Flask使用这个参数来肯定应用程序的根目录,这样之后能够相对这个路径来找到资源文件。后端
@app.route('/')
客户端例如web浏览器发送 请求 给web服务,进而将它们发送给Flask应用程序实例。应用程序实例须要知道对于各个URL请求须要运行哪些代码,因此它给Python函数创建了一个URLs映射。这些在URL和函数之间创建联系的操做被称之为 路由 。设计模式
在Flask应程序中定义路由的最便捷的方式是经过显示定义在应用程序实例之上的app.route装饰器,注册被装饰的函数来做为一个 路由。浏览器
在上一个示例给应用程序的根URL注册gello_world()函数做为事件的处理程序。若是这个应用程序被部署在服务器上并绑定了 www.example.com 域名,而后在你的浏览器地址栏中输入 http://www.example.com 将触发gello_world()来运行服务。客户端接收到的这个函数的返回值被称为 响应 。若是客户端是web浏览器,响应则是显示给用户的文档。服务器
相似于gello_world()的函数被称做 视图函数 。
你的Facebook我的信息页的URL是 http://www.facebook.com/
@app.route('/hello/<name>') def gello_world(name): return 'Hello World %s' % name
用尖括号括起来的部分是动态的部分,因此任何URLs匹配到静态部分都将映射到这个路由。当视图函数被调用,Flask发送动态组件做为一个参数。在前面的示例的视图函数中,这个参数是用于生成一个个性的问候做为响应。
在路由中动态组件默认为字符串,可是能够定义为其余类型。例如,路由/user/
以下:
@app.route('/hello/<int:id>') def gello_stu_id(id): return 'Hello World id: %s' % id
if __name__ == '__main__': app.run()
注意: __name__ == '__main__'在此处使用是用于确保web服务已经启动当脚本被当即执行。当脚本被另外一个脚本导入,它被看作父脚本将启动不一样的服务,因此app.run()调用会被跳过。
一旦服务启动,它将进入循环等待请求并为之服务。这个循环持续到应用程序中止,例如经过按下Ctrl-C。
有几个选项参数能够给app.run()配置web服务的操做模式。在开发期间,能够很方便的开启debug模式,将激活 debugger 和 reloader 。这样作是经过传递debug为True来实现的。
run()中参数有以下:
debug 是否开启调试模式,开启后修改python的代码会自动重启 port 启动指定服务器的端口号 host主机,默认是127.0.0.1
pip install flask-script
调整代码
manager = Manager(app=‘自定义的flask对象’)
启动的地方
manager.run()
python hellow.py runserver -h 地址 -p 端口 -d -r
其中:-h表示地址。-p表示端口。-d表示debug模式。-r表示自动重启
写法:
converter类型:
string 字符串 int 整形 float 浮点型 path 接受路径,接收的时候是str,/也当作字符串的一个字符 uuid 只接受uuid字符串 any 能够同时指定多种路径,进行限定
例子:
@app.route('/helloint/<int:id>/') @app.route('/getfloat/<float:price>/') @app.route('/getstr/<string:name>/',methods=['GET', 'POST']) @app.route('/getpath/<path:url_path>/') @app.route('/getbyuuid/<uuid:uu>/',methods=['GET', 'POST'])
实现对应的视图函数:
@blue.route('/hello/<name>/') def hello_man(name): print(type(name)) return 'hello name:%s type:%s' % (name, type(name)) @blue.route('/helloint/<int:id>/') def hello_int(id): print(id) print(type(id)) return 'hello int: %s' % (id) @blue.route('/index/') def index(): return render_template('hello.html') @blue.route('/getfloat/<float:price>/') def hello_float(price): return 'float: %s' % price @blue.route('/getstr/<string:name>/') def hello_name(name): return 'hello name: %s' % name @blue.route('/getpath/<path:url_path>/') def hello_path(url_path): return 'path: %s' % url_path @blue.route('/getuuid/') def gello_get_uuid(): a = uuid.uuid4() return str(a) @blue.route('/getbyuuid/<uuid:uu>/') def hello_uuid(uu): return 'uu:%s' % uu
经常使用的请求类型有以下几种
GET : 获取 POST : 建立 PUT : 修改(所有属性都修改) DELETE : 删除 PATCH : 修改(修改部分属性)
定义url的请求类型:
@blue.route('/getrequest/', methods=['GET', 'POST'])
在Flask项目中能够用Blueprint(蓝图)实现模块化的应用,使用蓝图可让应用层次更清晰,开发者更容易去维护和开发项目。蓝图将做用于相同的URL前缀的请求地址,将具备相同前缀的请求都放在一个模块中,这样查找问题,一看路由就很快的能够找到对应的视图,并解决问题了。
pip install flask_blueprint
blue = Blueprint(‘first’,\_\_name\_\_)
注意:Blueprint中传入了两个参数,第一个是蓝图的名称,第二个是蓝图所在的包或模块,__name__表明当前模块名或者包名
app = Flask(\_\_name\_\_) app.register_blueprint(blue, url_prefix='/user')
注意:第一个参数即咱们定义初始化定义的蓝图对象,第二个参数url_prefix表示该蓝图下,全部的url请求必须以/user开始。这样对一个模块的url能够很好的进行统一管理
修改视图上的装饰器,修改成@blue.router(‘/’)
@blue.route('/', methods=['GET', 'POST']) def hello(): # 视图函数 return 'Hello World'
注意:该方法对应的url为127.0.0.1:5000/user/
语法:
无参状况: url_for('蓝图中定义的第一个参数.函数名') 有参状况: url_for('蓝图中定义的第一个参数.函数名', 参数名=value)
定义跳转:
from flask import url_for, redirect # 第一步: 生成蓝图对象 blueprint = Blueprint('first', __name__) @blueprint.route('/') def hello(): return 'hello' @blueprint.route('/stu/<id>/') def stu(id): return 'hello stu: %s' % id # 1. 定义路由跳转到hello方法 @blueprint.route('/redirect/') def my_redirect(): # 第一种方法 # redirect: 跳转 # url_for: 反向解析 # 'first.hello': 蓝图第一个参数.跳转到的函数名 return redirect(url_for('first.hello')) # 第二种方法 return redirect('/hello/index/') # 2. 定义路由跳转到stu方法 @blueprint.route('/redirect_id/') def stu_redirect(): return redirect(url_for('first.stu', id=3))
注意: 反向解析可使用url_for方法,也能够直接定义跳转的路由地址。
语法:
无参形式: {{ url_for('蓝图中定义的第一个参数.函数名') }} 有参形式: {{ url_for('蓝图中定义的第一个参数.函数名',参数名=value) }}
服务端在接收到客户端的请求后,会自动建立Request对象
由Flask框架建立,Requesy对象不可修改
属性:
url:完整的请求地址 base_url:去掉GET参数的url host_url:只有主机和端口号的url path:路由中的路径 method:请求方法 remote_addr:请求的客户端的地址 args:GET请求参数 form:POST请求参数 files:文件上传 headers:请求头 cookies:请求中的cookie
a)args是get请求参数的包装,args是一个ImmutableMultiDict对象,类字典结构对象
b)数据存储也是key-value
c) 获取GET请求中传递的参数,request.args
a)form是post请求参数的包装,args是一个ImmutableMultiDict对象,类字典结构对象
b)数据存储也是key-value
c) 获取POST请求中传递的参数,request.form
重点:ImmutableMultiDict是相似字典的数据结构,可是与字典的区别是,能够存在相同的键。
在ImmutableMultiDict中获取数据的方式,dict['key']或者dict.get('key')或者dict.getlist('key')
Response是由开发者本身建立的
建立方法:
from flask import make_response make_response建立一个响应,是一个真正的Response对象
状态码:
格式:make_reponse(data,code),其中data是返回的数据内容,code是状态码
a)直接将内容当作make_response的第一个参数,第二个参数直接写返回的状态码 b)直接在render后加返回的状态码
例子1:
定义一个获取GET请求的request的方法,并将返回成功的请求的状态码修改成200
@blue.route('/getrequest/', methods=['GET']) def get_request(): print(request) return '获取request', 200
例子2:
返回response响应,并添加返回结果的状态码200
@blue.route('/getresponse/') def get_response(): response = make_response('<h2>我是响应</h2>', 500) return response
或者:
@blue.route('/getresponse/', methods=['GET']) def get_user_response(): login_html = render_template('login.html') res = make_response(login_html, 200) return res
自动抛出异常:abort(状态码)
捕获异常处理:errorhandler(状态码),定义的函数中要包含一个参数,用于接收异常信息
@blue.route('/make_abort/') def get_abort(): abort(400) return '终止'
@blue.errorhandler(400) def handler(exception): return '捕获到异常信息:%s' % exception