Flask拾遗总汇1
flask依赖wsgi,实现wsgi的模块:wsgiref,werkzeug,uwsgi
1.flask的路由分发方式
路由分发的本质:将url和视图函数封装成一个rule对象,添加到flask的url_map字段中
方式一: @app.route('/xxxx') # @decorator def index(): return "index" 方式二: def index(): return "index" app.add_url_rule('/xxx', "n1", index) #n1是别名
2.请求响应相关
- request - request.form #post请求 - request.args #get请求 字典形式的 - request.querystring #get请求,bytes形式的 - response - return render_tempalte() - return redirect() - return "" v = make_response(返回值) #吧返回的值包在了这个函数里面 - session - 存在浏览器上,并且是加密的 - 依赖于:secret_key
3.flask配置文件拾遗(config)
方式一: app.config['debug'] = true ps: 由于config对象本质上是字典,所以还可以使用app.config.update(...) 方式二: app.config.from_pyfile("python文件名称") 如: settings.py debug = true app.config.from_pyfile("settings.py")方式三: import os os.environ['flaks-settings'] = 'settings.py' app.config.from_envvar('flaks-settings') 方法四: 见下方from_object用法
app.config.from_envvar("环境变量名称") #环境变量的值为python文件名称名称,内部调用from_pyfile方法 app.config.from_json("json文件名称") #json文件名称,必须是json格式,因为内部会执行json.loads app.config.from_mapping({'debug':true}) #字典格式
from_object用法:
app.config.from_object("python类或类的路径") app.config.from_object('pro_flask.settings.testingconfig') settings.py class config(object): debug = false testing = false database_uri = 'sqlite://:memory:' class productionconfig(config): database_uri = 'mysql://user@localhost/foo' class developmentconfig(config): debug = true class testingconfig(config): testing = true ps: 从sys.path中已经存在路径开始写 ps: settings.py文件默认路径要放在程序root_path目录,如果instance_relative_config为true,则就是instance_path目录
current_app用法:
要想在视图函数中获取配置文件的值,都是通过app.config来拿。但是如果视图函数和flask创建的对象app不在一个模块。就得
导入来拿。可以不用导入。直接导入一个current_app,这个就是当前的app对象,用current_app.config就能查看到了当前app的所有的配置文件
from flask import flask,current_app @app.route('/index',methods=["get","post"]) def index(): print(current_app.config) #当前的app的所有配置 session["xx"] = "fdvbn" return "index"
4.路由系统参数配置
4.1 可传入参数:
@app.route('/user/<username>') #常用的 不加参数的时候默认是字符串形式的 @app.route('/post/<int:post_id>') #常用的 #指定int,说明是整型的 @app.route('/post/<float:post_id>') @app.route('/post/<path:path>') @app.route('/login', methods=['get', 'post'])
4.2 常用路由系统有以上五
所有的路由系统都是基于一下对应关系来处理:
default_converters = { 'default': unicodeconverter, 'string': unicodeconverter, 'any': anyconverter, 'path': pathconverter, 'int': integerconverter, 'float': floatconverter, 'uuid': uuidconverter, }
5.反向生成url: url_for
endpoint("name") #别名,相当于django中的name
反向解析需要导入:
from flask import flask, url_for @app.route('/index',endpoint="xxx") #endpoint是别名 def index(): v = url_for("xxx") print(v) return "index" @app.route('/zzz/<int:nid>',endpoint="aaa") #endpoint是别名 def zzz(nid): v = url_for("aaa",nid=nid) print(v) return "index2"
@app.route和app.add_url_rule参数:
# @app.route和app.add_url_rule参数: rule, # url规则 view_func, # 视图函数名称 defaults=none, # 默认值,当url中无参数,函数需要参数时,使用defaults={'k':'v'}为函数提供参数 endpoint=none, # 名称,用于反向生成url,即: url_for('名称') methods=none, # 允许的请求方式,如:["get","post"] strict_slashes=none, # 对url最后的 / 符号是否严格要求, # 如: # @app.route('/index',strict_slashes=false), # 访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可 # @app.route('/index',strict_slashes=true) # 仅访问 http://www.xx.com/index redirect_to=none, # 重定向到指定地址 # 如: # @app.route('/index/<int:nid>', redirect_to='/home/<nid>') # 或 # def func(adapter, nid): # return "/home/888" # @app.route('/index/<int:nid>', redirect_to=func) subdomain=none, # 子域名访问 from flask import flask, views, url_for app = flask(import_name=__name__) app.config['server_name'] = 'wxs.com:5000' @app.route("/", subdomain="admin") def static_index(): """flask supports static subdomains this is available at static.your-domain.tld""" return "admin.xxx.com" #动态生成 @app.route("/dynamic", subdomain="<username>") def username_index(username): """dynamic subdomains are also supported try going to user1.your-domain.tld/dynamic""" return username + ".your-domain.tld" if __name__ == '__main__': app.run() # 所有的域名都得与ip做一个域名解析: # 如果你想通过域名去访问,有两种解决方式: # 方式一: # 1、租一个域名 wxs.lalala # 2、租一个公网ip 49.8.5.62 # 3、域名解析: # wxs.com 49.8.5.62 # 4、吧代码放在49.8.5.62这个服务器上,程序运行起来 # 用户可以通过ip进行访问 # 方式二:如果是自己测试用的就可以用这种方式。先在自己本地的文件中找 # c:\windows\system32\drivers\etc 找到host,修改配置 # 然后吧域名修改成自己的本地服务器127.0.0.1 # 加上配置:app.config["server_name"] = "wxs.com:5000"
域名(subdomain)访问实例:
# =============== 子域名访问============ @app.route("/static_index", subdomain="admin") def static_index(): return "admin.bjg.com" # ===========动态生成子域名=========== @app.route("/index",subdomain='<xxxxx>') def index(xxxxx): return "%s.bjg.com" %(xxxxx,)
6.flask路由系统的正则匹配配置
扩展flask的路由系统,让他支持正则,这个类必须这样写,必须去继承baseconverter
from flask import flask,url_for app = flask(__name__) # 定义转换的类 from werkzeug.routing import baseconverter class regexconverter(baseconverter): """ 自定义url匹配正则表达式 """ def __init__(self, map, regex): super(regexconverter, self).__init__(map) self.regex = regex def to_python(self, value): """ 路由匹配时,匹配成功后传递给视图函数中参数的值 :param value: :return: """ return int(value) def to_url(self, value): """ 使用url_for反向生成url时,传递的参数经过该方法处理,返回的值用于生成url中的参数 :param value: :return: """ val = super(regexconverter, self).to_url(value) return val # 添加到converts中 app.url_map.converters['regex'] = regexconverter # 进行使用 @app.route('/index/<regex("\d+"):nid>',endpoint='xx') def index(nid): url_for('xx',nid=123) #反向生成,就会去执行to_url方法 return "index" if __name__ == '__main__': app.run()
7.flask中的cbv模式
def auth(func): def inner(*args, **kwargs): result = func(*args, **kwargs) return result return inner class indexview(views.methodview): # methods = ['post'] #只允许post请求访问 decorators = [auth,] #如果想给所有的get,post请求加装饰器,就可以这样来写,也可以单个指定 def get(self): #如果是get请求需要执行的代码 v = url_for('index') print(v) return "get" def post(self): #如果是post请求执行的代码 return "post" app.add_url_rule('/index', view_func=indexview.as_view(name='index')) #name指定的是别名,会当做endpoint使用 if __name__ == '__main__': app.run()
8.flask中的fbv模式
方式一: @app.route('/index',endpoint='xx') def index(nid): url_for('xx',nid=123) return "index" 方式二: def index(nid): url_for('xx',nid=123) return "index" app.add_url_rule('/index',index)
9.flask中的请求与相应
1 from flask import flask 2 from flask import request 3 from flask import render_template 4 from flask import redirect 5 from flask import make_response 6 7 app = flask(__name__) 8 9 10 @app.route('/login.html', methods=['get', "post"]) 11 def login(): 12 13 # 请求相关信息 14 # request.method 15 # request.args 16 # request.form 17 # request.values 18 # request.cookies 19 # request.headers 20 # request.path 21 # request.full_path 22 # request.script_root 23 # request.url 24 # request.base_url 25 # request.url_root 26 # request.host_url 27 # request.host 28 # request.files 29 # obj = request.files['the_file_name'] 30 # obj.save('/var/www/uploads/' + secure_filename(f.filename)) 31 32 # 响应相关信息 33 # return "字符串" 34 # return render_template('html模板路径',**{}) 35 # return redirect('/index.html') 36 37 # response = make_response(render_template('index.html')) 38 # response是flask.wrappers.response类型 39 # response.delete_cookie('key') 40 # response.set_cookie('key', 'value') 41 # response.headers['x-something'] = 'a value' 42 # return response 43 44 45 return "内容" 46 47 if __name__ == '__main__': 48 app.run()
请求与相应详解
from flask import flask,url_for,request,redirect,render_template,jsonify,make_response from urllib.parse import urlencode,quote,unquote app = flask(__name__) @app.route('/index',endpoint='xx') def index(): from werkzeug.datastructures import immutablemultidict ================= # get_data = request.args # get_dict = get_data.to_dict() # get_dict['xx'] = '18' # url = urlencode(get_dict) # print(url) ==================== # print(request.query_string) # print(request.args) ========================== # val = "%e6%8a%8a%e5%87%a0%e4%b8%aa" # print(unquote(val)) #吧上面这样的数据转换成中文 # # return "index" # return "index" # return redirect() # return render_template() # return jsonify(name='alex',age='18') #相当于jsonresponse ======================= response = make_response('xxxxx') #如果是返回更多的值,cookie,headers,或者其他的就可用它 response.headers['xxx'] = '123123' return response if __name__ == '__main__': # app.__call__ app.run()
10.flask模板语法(jinja2)
template_global和template_filter用法:
调用方式:{{sb(1,2)}} {{ 1|db(2,3)}}
@app.template_global() def sb(a1, a2): return a1 + a2 @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3
11.session
除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 cookies 的基础上实现的,并且对 cookies 进行密钥签名要使用会话,你需要设置一个密钥。
- 设置:session['username'] = 'xxx'
- 删除:session.pop('username', none)
from flask import flask,url_for,session app = flask(__name__) app.secret_key = "sdsfdgdgdgd" app.config['session_cookie_name'] = 'session_lvning' #设置session的名字 @app.route('/index/') def index(nid): #session本质上操作的是字典, session是否还有其他方法?与字典方法相同 #session的原理:如果下一次访问的时候带着随机字符串,会把session里面对应的 # 值拿到内存,假设session保存在数据库,每执行一次链接一次数据库,每次都要时时更新的话 # 会非常损耗内存 session["xxx"] = 123 session["xxx2"] = 123 session["xxx3"] = 123 session["xxx4"] = 123 del session["xxx2"] #在这删除了,真正存储的时候是没有xxx2的 return "ddsf" if __name__ == '__main__': app.run()
关于session的配置
app.config['session_cookie_name'] = 'session_lvning'
- session超时时间如何设置? 'permanent_session_lifetime': timedelta(days=31) 以下是跟session相关的配置文件 """ 'session_cookie_name': 'session', 'session_cookie_domain': none, 'session_cookie_path': none, 'session_cookie_httponly': true, 'session_cookie_secure': false, 'session_refresh_each_request': true, #是否每次都跟新 'permanent_session_lifetime': timedelta(days=31)
1 from flask import flask, session, redirect, url_for, escape, request 2 3 app = flask(__name__) 4 5 @app.route('/') 6 def index(): 7 if 'username' in session: 8 return 'logged in as %s' % escape(session['username']) 9 return 'you are not logged in' 10 11 @app.route('/login', methods=['get', 'post']) 12 def login(): 13 if request.method == 'post': 14 session['username'] = request.form['username'] 15 return redirect(url_for('index')) 16 return ''' 17 <form action="" method="post"> 18 <p><input type=text name=username> 19 <p><input type=submit value=login> 20 </form> 21 ''' 22 23 @app.route('/logout') 24 def logout(): 25 # remove the username from the session if it's there 26 session.pop('username', none) 27 return redirect(url_for('index')) 28 29 # set the secret key. keep this really secret: 30 app.secret_key = 'a0zr98j/3yx r~xhh!jmn]lwx/,?rt'
自定义session:
1 pip3 install flask-session 2 3 run.py 4 from flask import flask 5 from flask import session 6 from pro_flask.utils.session import mysessioninterface 7 app = flask(__name__) 8 9 app.secret_key = 'a0zr98j/3yx r~xhh!jmn]lwx/,?rt' 10 app.session_interface = mysessioninterface() 11 12 @app.route('/login.html', methods=['get', "post"]) 13 def login(): 14 print(session) 15 session['user1'] = 'alex' 16 session['user2'] = 'alex' 17 del session['user2'] 18 19 return "内容" 20 21 if __name__ == '__main__': 22 app.run() 23 24 session.py 25 #!/usr/bin/env python 26 # -*- coding:utf-8 -*- 27 import uuid 28 import json 29 from flask.sessions import sessioninterface 30 from flask.sessions import sessionmixin 31 from itsdangerous import signer, badsignature, want_bytes 32 33 34 class mysession(dict, sessionmixin): 35 def __init__(self, initial=none, sid=none): 36 self.sid = sid 37 self.initial = initial 38 super(mysession, self).__init__(initial or ()) 39 40 41 def __setitem__(self, key, value): 42 super(mysession, self).__setitem__(key, value) 43 44 def __getitem__(self, item): 45 return super(mysession, self).__getitem__(item) 46 47 def __delitem__(self, key): 48 super(mysession, self).__delitem__(key) 49 50 51 52 class mysessioninterface(sessioninterface): 53 session_class = mysession 54 container = {} 55 56 def __init__(self): 57 import redis 58 self.redis = redis.redis() 59 60 def _generate_sid(self): 61 return str(uuid.uuid4()) 62 63 def _get_signer(self, app): 64 if not app.secret_key: 65 return none 66 return signer(app.secret_key, salt='flask-session', 67 key_derivation='hmac') 68 69 def open_session(self, app, request): 70 """ 71 程序刚启动时执行,需要返回一个session对象 72 """ 73 sid = request.cookies.get(app.session_cookie_name) 74 if not sid: 75 sid = self._generate_sid() 76 return self.session_class(sid=sid) 77 78 signer = self._get_signer(app) 79 try: 80 sid_as_bytes = signer.unsign(sid) 81 sid = sid_as_bytes.decode() 82 except badsignature: 83 sid = self._generate_sid() 84 return self.session_class(sid=sid) 85 86 # session保存在redis中 87 # val = self.redis.get(sid) 88 # session保存在内存中 89 val = self.container.get(sid) 90 91 if val is not none: 92 try: 93 data = json.loads(val) 94 return self.session_class(data, sid=sid) 95 except: 96 return self.session_class(sid=sid) 97 return self.session_class(sid=sid) 98 99 def save_session(self, app, session, response): 100 """ 101 程序结束前执行,可以保存session中所有的值 102 如: 103 保存到resit 104 写入到用户cookie 105 """ 106 domain = self.get_cookie_domain(app) 107 path = self.get_cookie_path(app) 108 httponly = self.get_cookie_httponly(app) 109 secure = self.get_cookie_secure(app) 110 expires = self.get_expiration_time(app, session) 111 112 val = json.dumps(dict(session)) 113 114 # session保存在redis中 115 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) 116 # session保存在内存中 117 self.container.setdefault(session.sid, val) 118 119 session_id = self._get_signer(app).sign(want_bytes(session.sid)) 120 121 response.set_cookie(app.session_cookie_name, session_id, 122 expires=expires, httponly=httponly, 123 domain=domain, path=path, secure=secure)
第三方flask-session应用:
session存在在服务端的一个字典里面,session保存起来,取一次里面还是有的,直到你删除之后才没有了
from flask import flask, session, render_template, request, views from flask_session import session from redis import redis app = flask(__name__) app.default_config() app.config["session_type"] = "redis" app.config["session_redis"] = redis(host="127.0.0.1", port=6379, db=0) app.templates_auto_reload = true # 使用第三方flask-session,封装app这个实例化对象 session(app) userinfo = {"user": "alex", "pwd": "123"} class login(views.methodview): methods = ["post", "get"] def get(self): return render_template("login.html") def post(self): user = request.form.get("username") pwd = request.form.get("pwd") if user == userinfo["user"] and pwd == userinfo["pwd"]: # 创建session session["user"] = user return "登录成功!" else: return "登录失败!" app.add_url_rule("/login", endpoint=none, view_func=login.as_view(name="login")) if __name__ == '__main__': app.run()
12.闪现 : flash
本质:flash是基于session创建的,flash支持往里边放值,只要你取一下就没有了,相当于pop了一下。不仅把值取走,而且把session里的东西去掉
from flask import flask,session,session,flash,get_flashed_messages,redirect,render_template,request app = flask(__name__) app.secret_key ='sdfsdfsdf' @app.route('/users') def users(): # 方式一 # msg = request.args.get('msg','') # 方式二 # msg = session.get('msg') # if msg: # del session['msg'] # 方式三 v = get_flashed_messages() print(v) msg = '' return render_template('users.html',msg=msg) @app.route('/useradd') def user_add(): # 在数据库中添加一条数据 # 假设添加成功,在跳转到列表页面时,显示添加成功 # 方式一 # return redirect('/users?msg=添加成功') # 方式二 # session['msg'] = '添加成功' # 方式三 flash('添加成功') return redirect('/users') if __name__ == '__main__': app.run(debug=true)