首页 技术 正文
技术 2022年11月20日
0 收藏 324 点赞 5,067 浏览 5444 个字

Flask

官网:http://flask.pocoo.org/

  flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。

  “微”(micro) 并不表示你需要把整个 Web 应用塞进单个 Python 文件(虽然确实可以 ),也不意味着 Flask 在功能上有所欠缺。微框架中的“微”意味着 Flask 旨在保持核心简单而易于扩展。Flask 不会替你做出太多决策——比如使用何种数据库。而那些 Flask 所选择的——比如使用何种模板引擎——则很容易替换。除此之外的一切都由可由你掌握。如此,Flask 可以与您珠联璧合。

  默认情况下,Flask 不包含数据库抽象层、表单验证,或是其它任何已有多种库可以胜任的功能。然而,Flask 支持用扩展来给应用添加这些功能,如同是 Flask 本身实现的一样。众多的扩展提供了数据库集成、表单验证、上传处理、各种各样的开放认证技术等功能。Flask 也许是“微小”的,但它已准备好在需求繁杂的生产环境中投入使用。

安装

pip install Flask
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from werkzeug.wrappers import Request, Response@Request.application
def hello(request):
return Response('Hello World!')if __name__ == '__main__':
from werkzeug.serving import run_simple
run_simple('localhost', 4000, hello)

werkzeug

一、第一次

from flask import Flask
app = Flask(__name__)@app.route("/")
def hello():
return "Hello World!"if __name__ == "__main__":
app.run()

二、路由系统

  • @app.route(‘/user/<username>’)
  • @app.route(‘/post/<int:post_id>’)
  • @app.route(‘/post/<float:post_id>’)
  • @app.route(‘/post/<path:path>’)
  • @app.route(‘/login’, methods=[‘GET’, ‘POST’])

常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:

DEFAULT_CONVERTERS = {
'default': UnicodeConverter,
'string': UnicodeConverter,
'any': AnyConverter,
'path': PathConverter,
'int': IntegerConverter,
'float': FloatConverter,
'uuid': UUIDConverter,
}

注:对于Flask默认不支持直接写正则表达式的路由,不过可以通过自定义来实现,见:https://segmentfault.com/q/1010000000125259  

三、模板

1、模板的使用

Flask使用的是Jinja2模板,所以其语法和Django无差别

2、自定义模板方法

Flask中自定义模板方法的方式和Bottle相似,创建一个函数并通过参数的形式传入render_template,如:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>自定义函数</h1>
{{ww()|safe}}</body>
</html>

index.html

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template
app = Flask(__name__)def myfunc():
return '<h1>Redhat</h1>'@app.route('/login', methods=['GET', 'POST'])
def login():
return render_template('index.html', ww=myfunc)app.run()

四、公共组件

1、请求

对于Http请求,Flask会讲请求信息封装在request中(werkzeug.wrappers.BaseRequest),提供的如下常用方法和字段以供使用:

request.method
request.args
request.form
request.values
request.files
request.cookies
request.headers
request.path
request.full_path
request.script_root
request.url
request.base_url
request.url_root
request.host_url
request.host
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)

表单处理

from flask import request
from werkzeug import secure_filename@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
...

上传文件

from flask import request@app.route('/setcookie/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.from flask import make_response@app.route('/getcookie')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp

cookie处理

2、响应

当用户请求被开发人员的逻辑处理完成之后,会将结果发送给用户浏览器,那么就需要对请求做出相应的响应。

a.字符串

@app.route('/index/', methods=['GET', 'POST'])
def index():
return "index"

b.模板引擎

from flask import Flask,render_template,request
app = Flask(__name__)@app.route('/index/', methods=['GET', 'POST'])
def index():
return render_template("index.html")app.run()

c.重定向

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask, redirect, url_for
app = Flask(__name__)@app.route('/index/', methods=['GET', 'POST'])
def index():
# return redirect('/login/')
return redirect(url_for('login'))@app.route('/login/', methods=['GET', 'POST'])
def login():
return "LOGIN"app.run()

d.错误页面

from flask import Flask, abort, render_template
app = Flask(__name__)@app.route('/e1/', methods=['GET', 'POST'])
def index():
abort(404, 'Nothing')
app.run()

指定URL,简单错误

from flask import Flask, abort, render_template
app = Flask(__name__)@app.route('/index/', methods=['GET', 'POST'])
def index():
return "OK"@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404app.run()

e.设置相应信息

使用make_response可以对相应的内容进行操作

from flask import Flask, abort, render_template,make_response
app = Flask(__name__)@app.route('/index/', methods=['GET', 'POST'])
def index():
response = make_response(render_template('index.html'))
# response是flask.wrappers.Response类型
# response.delete_cookie
# response.set_cookie
# response.headers['X-Something'] = 'A value'
return responseapp.run()

3、Session

除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。

  • 设置:session[‘username’] = ‘xxx’

  • 删除:session.pop(‘username’, None)
from flask import Flask, session, redirect, url_for, escape, requestapp = Flask(__name__)@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
'''@app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index'))# set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

Flask还有众多其他功能,更多参见:
    http://docs.jinkan.org/docs/flask/
    http://flask.pocoo.org/

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,474
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,889
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,724
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,479
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,118
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,278