一、简单的Flask框架
1)flask简介
Flask 是一个 web 框架。也就是说 Flask 为你提供工具,库和技术来允许你构建一个 web 应用程序。 这个 wdb 应用程序可以使一些 web 页面、博客、wiki、基于 web 的日历应用或商业网站。 Flask 属于微框架(micro-framework)这一类别,微架构通常是很小的不依赖于外部库的框架。 这既有优点也有缺点,优点是框架很轻量,更新时依赖少,并且专注安全方面的 bug, 缺点是,你不得不自己做更多的工作,或通过添加插件增加自己的依赖列表。Flask 的依赖如下: Werkzeug 一个 WSGI 工具包 jinja2 模板引擎 安装:pip install flask
2)最简单的使用flask框架
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run()
二、Flask框架的组成部分
1)常见的路由系统
@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, }
使用示例
@app.route('/test/<any(about,help,import,class,"foo.bar"):page_name>') def test(page_name): return page_name
2)模板使用。
from flask import Flask,render_template,request # 静态文件和模板路径配置 app = Flask(__name__) def jinxin(): return "<a>活久见</a>" # 设置请求方式 @app.route("/index/",methods=['GET','POST']) def hello(): # return "Hello World!" # 获取用户请求数据: http://127.0.0.1:5000/index/?k=18 print(request.args) # ImmutableMultiDict([('k', '18')]) return render_template('index.html', k1='root', k2=[1,2,3], k3={'name':'user','age':22}, k4=jinxin) if __name__ == "__main__": # IP和端口配置 app.run()
模板中使用:包含了字符串,列表,字典,以及函数的传值调用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>index 首页</h1> <h3>{{k1}}</h3> <ul> {% for item in k2 %} <li>{{item}}</li> {% endfor %} </ul> <ul> {% for k,v in k3.items() %} <li>{{k}}-{{v}}</li> {% endfor %} </ul> {{k4()|safe}} </body> </html>
3)对于Http请求,Flask会讲请求信息封装在request中
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
3.1)表单处理示例。request.form
@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)
3.2)上传文件示例。request.files
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)) ...
3.3)cookies操作示例。request.cookies
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
3.4)用户请求数据。request.args
@app.route("/index/",methods=['GET','POST']) def hello(): # 获取用户请求数据: http://127.0.0.1:5000/index/?k=18 print(request.args) # ImmutableMultiDict([('k', '18')]) return ....
三、http请求的响应,返回用户的数据。即return的内容
1)返回字符串
@app.route('/index/', methods=['GET', 'POST']) def index(): return "index"
2)返回前端模板
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()
3)重定向。跳转
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()
4)指定错误页面
对于找不到路由的指向与404:from flask import Flask, abort
@app.route('/e1/', methods=['GET', 'POST']) def index(): abort(404, 'Nothing')
为404指定前端页面
@app.errorhandler(404) def page_not_found(error): return render_template('page_not_found.html'), 404
5)使用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 response app.run()
四、session操作.message操作,中间键等
1.1)session操作简介
除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的, 并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。 设置:session['username'] = 'xxx' 删除:session.pop('username', No
1.2)session操作示例
from flask import Flask, session, redirect, url_for, escape, request app = 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'
2)message是一个基于Session实现的用于保存数据的集合,flash方法。其特点是:使用一次就删除
from flask import Flask, flash, redirect, render_template, request app = Flask(__name__) app.secret_key = 'some_secret' @app.route('/') def index1(): return render_template('index.html') @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' if __name__ == "__main__": app.run()
前端展示
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> {% with messages = get_flashed_messages() %} {% if messages %} <ul class=flashes> {% for message in messages %} <li>{{ message }}</li> {% endfor %} </ul> {% endif %} {% endwith %} </body> </html>
3)自定义中间键。environ, start_response
自定义中间件
from flask import Flask,render_template,request,make_response,redirect,url_for,session app = Flask(__name__) @app.route("/index/",methods=['GET','POST']) def hello(): print('在路由中') return 'OK' class Foo: def __init__(self,w): self.w = w def __call__(self, environ, start_response): print("进入路由之前") obj = self.w(environ, start_response) print("进入路由之后") return obj if __name__ == "__main__": # app.wsgi_app = my_wsgi_app # 11. 自定制中间件 app.wsgi_app = Foo(app.wsgi_app) app.run()
标准写法改良
from flask import Flask, flash, redirect, render_template, request app = Flask(__name__) app.secret_key = 'some_secret' @app.route('/') def index1(): return render_template('index.html') @app.route('/set') def index2(): v = request.args.get('p') flash(v) return 'ok' class MiddleWare: def __init__(self,wsgi_app): self.wsgi_app = wsgi_app def __call__(self, *args, **kwargs): return self.wsgi_app(*args, **kwargs) if __name__ == "__main__": app.wsgi_app = MiddleWare(app.wsgi_app) app.run(port=9999)