Hello Flask

Hello Flask Flask简介

Hello Flask


Flask是一个使用Python编写的轻量级Web应用框架。基于Werkzeug WSGI工具箱和Jinja2 模板引擎。Flask使用BSD授权。
Flask被称为“microframework”,因为它使用简单的核心,用extension增加其他功能。Flask没有默认使用的数据库、窗体验证工具。然而,Flask保留了扩增的弹性,可以用Flask-extension加入这些功能:ORM、窗体验证工具、文件上传、各种开放式身份验证技术。
Flask英文翻译为瓶子,烧瓶,与另一个web框架Bottle同义,意在表示另一种容器,另一个框架。而且他们两个也有一些相似的地方。

第一个Flask程序 from flask import Flask app = Flask(__name__) @app.route('http://www.likecs.com/') def index(): return '<h1>Hello,Flask<h1/>' app.run('127.0.0.1',8000)

运行后可见控制台输出:

Serving Flask app “hello” (lazy loading)

Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.

Debug mode: off

Running on :8000/ (Press CTRL+C to quit)

URL路由

Flask路由采用装饰器的方式

@app.route('http://www.likecs.com/')   def index(): 绑定多个路由 @app.route('/index') @app.route('http://www.likecs.com/') def index(): 动态路由 @app.route('/index/<name>') def index(name):

name会作为参数传入视图函数
也可以为参数设置默认值:

@app.route('/index',defaults={'name':'sfencs'}) @app.route('/index/<name>') def index(name):

它其实相当于

@app.route('/index') @app.route('/index/<name>') def index(name='sfencs'):

还可以指定参数的类型:

@app.route('/index/<int:num>') def index(num):

这样路由只会匹配index后是数值类型参数的url,并且还会把num转换为int型
除了int之外还有path,string,float,any,uuid等

指定请求方式的路由 @app.route('/index/<int:num>',methods=['get']) def index(num):

method参数是一个列表

使用url_for()获取url

当视图函数绑定的路由发送改变时,我们可能在其他使用该路径的地方一个一个手动修改,这种硬编码的方式降低了代码的易用性,这种情况可以使用url_for()函数来获取url
url_for()函数的参数为视图函数名
例如

@app.route('/index') def aaa():

那么url_for(’aaa‘)就是’/index’
当然如果是有参数的路由,那么需要在url_for()函数中传入参数
例如

@app.route('/index/<int:num>') def aaa(num):

url_for函数就应该写为:url_for(‘aaa’,num=123)
url_for()函数默认生成的是相对URL,要想生成绝对URL需要加入参数_external=True

http请求与响应 请求

如何在视图函数中获取请求,首先需要引入request对象

from flask import Flask,request

在视图函数中可以直接通过request获得属性或方法
举个简单的例子

@app.route('/index/<int:num>',methods=['get']) def index(num): print(request.method) print(request.args.get('name','sfencs')) return '<h1>Hello,Flask<h1/>'

request中的方法和属性未来都会对我们很有用,这里就不一一介绍了。

响应 1.普通响应 return '<h1>Hello,Flask<h1/>' return '<h1>Hello,Flask<h1/>',200 #可以设置状态码 2.重定向 return redirect(url_for('index')) 3.错误响应 abort(404)

abort()函数直接返回错误响应,后面的代码不再执行

4.返回响应对象 response = make_response('<h1>Hello,Flask<h1/>') response.mimetype = 'text/html' return response

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzfjg.html