zoukankan      html  css  js  c++  java
  • 请求响应,session,闪现

    请求相关

     # 请求相关信息
            # request.method
            # request.args
            # request.form
            # request.values
            # 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
            # request.files
            # obj = request.files['the_file_name']
            # obj.save('/var/www/uploads/' + secure_filename(f.filename))

    响应相关

    # return "字符串"
    # return render_template('html模板路径',**{})
    # return redirect('/index.html')
    #return jsonify({'k1':'v1'})
    
    如果想写cooike,写headers,先用make_response包装一下
    # response = make_response(render_template('index.html'))
    # response是flask.wrappers.Response类型
    # response.delete_cookie('key')
    # response.set_cookie('key', 'value')
    # response.headers['XXXXXX'] = 'YYYYYY'
    # return response
    return "内容"
    from flask import Flask,request
    
    app=Flask(__name__)
    
    @app.route('/',methods=['GET','POST'])
    def index():
        print(request.args)        #ImmutableMultiDict([('name', 'pdun')])
        print(request.form)        # ImmutableMultiDict([('age', '1')])
        print(request.method)     #POST
        print(request.values)
      #CombinedMultiDict([ImmutableMultiDict([('name', 'pdun')]), ImmutableMultiDict([('age', '1')])])
    
    
        print(request.cookies)
        print(request.headers)
        print(request.path)
        print(request.full_path)
        print(request.script_root)
        print(request.url)                    #http://127.0.0.1:5000/?name=pdun
        print(request.base_url)            #http://127.0.0.1:5000/
        print(request.url_root)             #http://127.0.0.1:5000/
        print(request.host_url)               #http://127.0.0.1:5000/
        print(request.host)                    #127.0.0.1:5000
        print(request.files)
        return 'ok'
    
    if __name__ == '__main__':
        app.run()
    View Code

     二、session

    Flask中的session非常奇怪,他会将Session存放在客户端的Cookie中,使用起来也非常奇怪

    1、Flask中的session是需要secret

    from flask import session
    app = Flask(__name__)
    app.secret_key = "dsfsdgfsdgfg"
    
    #secret_key 实际上是用来加密字符串的,如果在实例化的app中没有 secret_key 那么开启session一定会抛异常的

    2、session要这样用

    @app.route("/login", methods=["GET", "POST"])
    def login():
        if request.method == "POST":
            if request.form["username"] == USER["username"] and request.form["password"] == USER["password"]:
                session["user"] = USER["username"]
                return redirect("/student_list")
            return render_template("login.html", msg="用户名密码错误")
    
        return render_template("login.html", msg=None)  # 如果前端Jinja2模板中使用了msg,这里就算是传递None也要出现msg

    3、cookie中的session到底是什么

    #cookies 中 session 存储的是通过 secret_key 加密后的 key , 通过这个 key 从flask程序的内存中找到用户对应的session信息

    4、用session进行验证

    @app.route("/student_list")
    def student():
        if session.get("user"):
            return render_template("student_list.html", student=STUDENT_DICT)
    
        return redirect("/login")

    session的简单使用

    from flask import Flask,session
    
    app=Flask(__name__)
    app.secret_key='sdfgfsfdgs'      #需要写这么一步
    @app.route('/')
    def index():
        session['name']='pdun'
        return 'index'
    
    
    @app.route('/text',methods=['GET','POST'])
    def text():
        print(session['name'])
        return 'text'
    if __name__ == '__main__':
        app.run()

    session源码

    如果不想把数据存放到cooike,存到redis等,写一个类
    app.session_interface=自己写的类,类中至少实现以下两个方法
     def open_session(self, app, request):
     def save_session(self, app, session, response): 
    
    
    ------------------------------------------------------
    读源码,
    
    app.session_interface                #点进去,
    session_interface = SecureCookieSessionInterface()   #点进去
    
    
    class SecureCookieSessionInterface(SessionInterface):    #类中又三个方法
        def get_signing_serializer(self, app):
    
        def open_session(self, app, request):
    
        def save_session(self, app, session, response):     #先看第三个方法
            if not session:          #  1、判断服务端是否存有session    
                if session.modified:      #没有session,判断是否被修改
                    response.delete_cookie(
                        app.session_cookie_name, domain=domain, path=path
                    )           #把cookie删除,重新添加
    
                return    
    
            if session.accessed:       #2、有session
                response.vary.add("Cookie")      #添加cooike
    
            if not self.should_set_cookie(app, session):
                return
    
            httponly = self.get_cookie_httponly(app)       #这几个是限制条件
            secure = self.get_cookie_secure(app)
            samesite = self.get_cookie_samesite(app)
            expires = self.get_expiration_time(app, session)
            val = self.get_signing_serializer(app).dumps(dict(session))
            response.set_cookie(
                app.session_cookie_name,
                val,
                expires=expires,
                httponly=httponly,
                domain=domain,
                path=path,
                secure=secure,
                samesite=samesite,
    ------------------------------------------------------------------
    看看类中的第二个方法
        def open_session(self, app, request):
            s = self.get_signing_serializer(app)
            if s is None:
                return None
            val = request.cookies.get(app.session_cookie_name)     #取val
            if not val:       #判断val是否存在
                return self.session_class()
            max_age = total_seconds(app.permanent_session_lifetime) #是否超时
            try:
                data = s.loads(val, max_age=max_age)
                return self.session_class(data)
            except BadSignature:
                return self.session_class()
    View Code

    闪现(基于session)

    #应用:对临时数据操作,如:展示错误信息
    
    from flask import Flask,flash,get_flashed_messages
        设置:flash('设置值')
        取值:get_flashed_message()  
    
    #存几次,几次就能取完

    示例

    from flask import Flask,session,flash,get_flashed_messages
    
    app=Flask(__name__)
    app.secret_key='sdfgfsfdgs'       #基于session,所以要加上加密方式
    @app.route('/')
    def index():
        flash('存值')
        return 'index'
    
    
    @app.route('/text',methods=['GET','POST'])
    def text():
        data=get_flashed_messages()
    
        print(data)
        return 'text'
    
    @app.route('/text2',methods=['GET','POST'])
    def text1():
        data=get_flashed_messages()
        flash('我也放一次,看text能不能取')
        print(data)
        return 'text2'
    if __name__ == '__main__':
        app.run()
    View Code
  • 相关阅读:
    mysql主从原理
    mysql锁和事物隔离
    mysql索引查找原理及调优
    MySQL高级查询
    周总结04
    冲刺第六天
    冲刺第五天
    冲刺第四天
    典型用户模板和用户场景模版
    冲刺第三天
  • 原文地址:https://www.cnblogs.com/pdun/p/11203082.html
Copyright © 2011-2022 走看看