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)
posted @ 2019-11-22 20:44  626  阅读(307)  评论(0编辑  收藏  举报