• flask


    1.Flask:

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

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

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

    安装:pip3 install flask

    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
    View Code

    2. 虚拟环境

    安装:   pip3 install virtualenv
            
            # 创建虚拟环境
            virtualenv env1 
            
            # 进入虚拟环境
                   Scripts/activate
            
            # 退出虚拟环境
                  Scripts/deactivate

    3.flask框架

         简介:轻量级框架
                      Django:无socket、中间件、路由系统、视图(CBV,FBV)、 模板、ORM、cookie、Session、Admin、Form、缓存、                                   信号、序列化....
                         Flask:无socket、中间件(扩展)、路由系统、视图(CBV)、第三方模板(jinja2)、cookie、Session弱爆了

                       a. 什么是wsgi?
                               Web服务网管接口,协议。

                       b. Flask依赖一个实现了WSGI协议的模块:werkzeug

    flask

          -依赖于wsgi模块:wsgiref,werkzeug,wsgi

          -实例化Flask对象

               -静态文件前缀  /xxx

               -静态文件目录

               -模板路径

         添加路由关系

               -将 Rule(url和视图函数)添加到Flask对象的url_map字段中

               -两种添加路由的方式

         request

              -request.form

              -request.args 

    4.基本使用:

    from flask import Flask

    # 实例化Flask对象
    app = Flask(__name__)

    # 生成路由关系,并把关系保存到某个地方,app对象的 url_map字段中
    @app.route('/xxxx') # @decorator
    def index():
    return "Index"

    # def index():
    # return "Index"
    # app.add_url_rule('/xxx', "n1", index)

    if __name__ == '__main__':
    # 启动程序,监听用户请求
    # 一旦请求到来,执行 app.__call__方法
    # 封装用户请求
    # 进行路由匹配
    app.run()


    练习:

    from flask import Flask,render_template,request,redirect,session
    app = Flask(__name__)
    app.secret_key = "sdsfdsgdfgdfgfh"
    
    def wrapper(func):
        def inner(*args,**kwargs):
            if not session.get("user_info"):
                return redirect("/login")
            ret = func(*args,**kwargs)
            return ret
        return inner
    
    @app.route("/login",methods=["GET","POST"])
    def login():
        if request.method=="GET":
            return render_template("login.html")
        else:
            # print(request.values)   #这个里面什么都有,相当于body
            username = request.form.get("username")
            password = request.form.get("password")
            if username=="haiyan" and password=="123":
                session["user_info"] = username
                # session.pop("user_info")  #删除session
                return redirect("/index")
            else:
                # return render_template("login.html",**{"msg":"用户名或密码错误"})
                return render_template("login.html",msg="用户名或者密码错误")
    
    @app.route("/index",methods=["GET","POST"])
    @wrapper
    def index():
        # if not session.get("user_info"):
        #     return redirect("/login")
        return render_template("index.html")
    
    
    if __name__ == '__main__':
        app.run(debug=True)

    保存session的数据存到了浏览器上,
      - 优点:减轻了服务端的压力
      - 缺点:不安全

    5.路由系统:

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

        路由系统

          -可传入参数

               @app.route('/user/<username>')

               @qpp.route('/post/<int:post_id>',methods=['GET','POST'],endpoint='fff')

         -反向生成URL:url_for

         -重定向

         -扩展Flask的路由系统,让它支持正则:

    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['xxx'] = RegexConverter
    
                    # 进行使用
                    @app.route('/index/<xxx("d+"):nid>',endpoint='xx')
                    def index(nid):
                        url_for('xx',nid=123)
                        return "Index"
    
                    if __name__ == '__main__':
                        app.run()

    6.视图函数

    Django:
                /index/    func
                
                /index/    IndexClass.as_view()
                
            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)
                    
                CBV:
                    def auth(func):
                        def inner(*args, **kwargs):
                            result = func(*args, **kwargs)
                            return result
                        return inner
    
                    class IndexView(views.MethodView):
                        # methods = ['POST']
    
                        decorators = [auth,]       #静态字段
    
                        def get(self):
                            v = url_for('index')
                            print(v)
                            return "GET"
    
                        def post(self):
                            return "GET"
    
                    app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))
    
                    if __name__ == '__main__':
                        app.run()

    6.请求响应

    from flask import Flask
        from flask import request
        from flask import render_template
        from flask import redirect
        from flask import make_response
    
        app = Flask(__name__)
    
    
        @app.route('/login.html', methods=['GET', "POST"])
        def login():
    
            # 请求相关信息
            # 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')
    
            # response = make_response(render_template('index.html'))
            # response是flask.wrappers.Response类型
            # response.delete_cookie('key')
            # response.set_cookie('key', 'value')
            # response.headers['X-Something'] = 'A value'
            # return response
    
    
            return "内容"
    
        if __name__ == '__main__':
            app.run()
    请求响应

        - from urllib.parse import urlencode,quote,unquote
        - make_response

    在django中用make_safe而在Flask中用make_response

    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')
    
        response = make_response('xxxxx')
        response.headers['xxx'] = '123123'
        return response
    
    
    if __name__ == '__main__':
        # app.__call__
        app.run()

    7.模板语言   

         a、模板的使用

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

         b、自定义模板方法

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

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <h1>自定义函数</h1>
        {{ww()|safe}}
    
    </body>
    </html>
    
    html
    html
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from flask import Flask,render_template
    app = Flask(__name__)
     
     
    def wupeiqi():
        return '<h1>Wupeiqi</h1>'
     
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        return render_template('login.html', ww=wupeiqi)
     
    app.run()
    
    run.py
    run
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    
        {% macro input(name, type='text', value='') %}
            <input type="{{ type }}" name="{{ name }}" value="{{ value }}">
        {% endmacro %}
    
        {{ input('n1') }}
    
        {% include 'tp.html' %}
    
        <h1>asdf{{ v.k1}}</h1>
    </body>
    </html>
    
    其他
    其他

    8.session

         -session是否还有其他方法?

                 -它与字典方法相同

        -session超时时间如何设置:

    app.config['SESSION_COOKIE_NAME'] = 'session_lvning'
                """
                '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)

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

    • 设置:session['username'] = 'xxx'

    • 删除:session.pop('username', None)
    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'
    基本使用
    pip3 install Flask-Session
            
            run.py
                from flask import Flask
                from flask import session
                from pro_flask.utils.session import MySessionInterface
                app = Flask(__name__)
    
                app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
                app.session_interface = MySessionInterface()
    
                @app.route('/login.html', methods=['GET', "POST"])
                def login():
                    print(session)
                    session['user1'] = 'alex'
                    session['user2'] = 'alex'
                    del session['user2']
    
                    return "内容"
    
                if __name__ == '__main__':
                    app.run()
    
            session.py
                #!/usr/bin/env python
                # -*- coding:utf-8 -*-
                import uuid
                import json
                from flask.sessions import SessionInterface
                from flask.sessions import SessionMixin
                from itsdangerous import Signer, BadSignature, want_bytes
    
    
                class MySession(dict, SessionMixin):
                    def __init__(self, initial=None, sid=None):
                        self.sid = sid
                        self.initial = initial
                        super(MySession, self).__init__(initial or ())
    
    
                    def __setitem__(self, key, value):
                        super(MySession, self).__setitem__(key, value)
    
                    def __getitem__(self, item):
                        return super(MySession, self).__getitem__(item)
    
                    def __delitem__(self, key):
                        super(MySession, self).__delitem__(key)
    
    
    
                class MySessionInterface(SessionInterface):
                    session_class = MySession
                    container = {}
    
                    def __init__(self):
                        import redis
                        self.redis = redis.Redis()
    
                    def _generate_sid(self):
                        return str(uuid.uuid4())
    
                    def _get_signer(self, app):
                        if not app.secret_key:
                            return None
                        return Signer(app.secret_key, salt='flask-session',
                                      key_derivation='hmac')
    
                    def open_session(self, app, request):
                        """
                        程序刚启动时执行,需要返回一个session对象
                        """
                        sid = request.cookies.get(app.session_cookie_name)
                        if not sid:
                            sid = self._generate_sid()
                            return self.session_class(sid=sid)
    
                        signer = self._get_signer(app)
                        try:
                            sid_as_bytes = signer.unsign(sid)
                            sid = sid_as_bytes.decode()
                        except BadSignature:
                            sid = self._generate_sid()
                            return self.session_class(sid=sid)
    
                        # session保存在redis中
                        # val = self.redis.get(sid)
                        # session保存在内存中
                        val = self.container.get(sid)
    
                        if val is not None:
                            try:
                                data = json.loads(val)
                                return self.session_class(data, sid=sid)
                            except:
                                return self.session_class(sid=sid)
                        return self.session_class(sid=sid)
    
                    def save_session(self, app, session, response):
                        """
                        程序结束前执行,可以保存session中所有的值
                        如:
                            保存到resit
                            写入到用户cookie
                        """
                        domain = self.get_cookie_domain(app)
                        path = self.get_cookie_path(app)
                        httponly = self.get_cookie_httponly(app)
                        secure = self.get_cookie_secure(app)
                        expires = self.get_expiration_time(app, session)
    
                        val = json.dumps(dict(session))
    
                        # session保存在redis中
                        # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)
                        # session保存在内存中
                        self.container.setdefault(session.sid, val)
    
                        session_id = self._get_signer(app).sign(want_bytes(session.sid))
    
                        response.set_cookie(app.session_cookie_name, session_id,
                                            expires=expires, httponly=httponly,
                                            domain=domain, path=path, secure=secure)
    
    自定义Session
    自定义session
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    """
    pip3 install redis
    pip3 install flask-session
    
    """
    
    
    from flask import Flask, session, redirect
    from flask.ext.session import Session
    
    
    app = Flask(__name__)
    app.debug = True
    app.secret_key = 'asdfasdfasd'
    
    
    app.config['SESSION_TYPE'] = 'redis'
    from redis import Redis
    app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379')
    Session(app)
    
    
    @app.route('/login')
    def login():
        session['username'] = 'alex'
        return redirect('/index')
    
    
    @app.route('/index')
    def index():
        name = session['username']
        return name
    
    
    if __name__ == '__main__':
        app.run()
    第三方session

    9.请求扩展

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    from flask import Flask, Request, render_template
    
    app = Flask(__name__, template_folder='templates')
    app.debug = True
    
    
    @app.before_first_request
    def before_first_request1():
        print('before_first_request1')
    
    
    @app.before_first_request
    def before_first_request2():
        print('before_first_request2')
    
    
    @app.before_request
    def before_request1():
        Request.nnn = 123
        print('before_request1')
    
    
    @app.before_request
    def before_request2():
        print('before_request2')
    
    
    @app.after_request
    def after_request1(response):
        print('before_request1', response)
        return response
    
    
    @app.after_request
    def after_request2(response):
        print('before_request2', response)
        return response
    
    
    @app.errorhandler(404)
    def page_not_found(error):
        return 'This page does not exist', 404
    
    
    @app.template_global()
    def sb(a1, a2):
        return a1 + a2
    
    
    @app.template_filter()
    def db(a1, a2, a3):
        return a1 + a2 + a3
    
    
    @app.route('/')
    def hello_world():
        return render_template('hello.html')
    
    
    if __name__ == '__main__':
        app.run()
    调用方式:{{sb(1,2)}}  {{ 1|db(2,3)}}

    10.闪现(flash)

    session从在在服务端的一个字典中,session保存的数据取一次,它还是会有。而flash是基于session创建的,flash支持在里面放值,只要在里面取值它就会没有。闪现就是

    在session的基础上,把它的值真实的放在session上,当去它的时候不仅把它的值取走,还把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()

    11.蓝图

    蓝图用于为应用提供目录划分

      • 蓝图URL前缀:xxx = Blueprint('account', __name__,url_prefix='/xxx')
      • 蓝图子域名:xxx = Blueprint('account', __name__,subdomain='admin')
        # 前提需要给配置SERVER_NAME: app.config['SERVER_NAME'] = 'wupeiqi.com:5000'
        # 访问时:admin.wupeiqi.com:5000/login.html

    12.配置文件

    1. 配置文件
            a. 以后遇到 xxx['xx'] = 123
                - __setitem__
                - 继承dict
                PS: 
                    class Foo(dict):
                        def __init__(self,val):
                            dict.__init__(self,val)
    
                    obj = Foo({'xxx':123})
                    print(obj)
                            
            b. 配置方式
                # 方式一:
                # app.config['SESSION_COOKIE_NAME'] = 'session_lvning'  #
                # 方式二:
                # app.config.from_pyfile('settings.py')
                # 方式三:
                # import os
                # os.environ['FLAKS-SETTINGS'] = 'settings.py'
                # app.config.from_envvar('FLAKS-SETTINGS')
                # 方式四:
                # app.config.from_object('settings.DevConfig')

    14.中间件

    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)

     

          

           

  • 相关阅读:
    不参加IT培训,如何通过自学的方式成功转行?(蜗牛学院)
    惠普电脑win10关闭自动调节亮度
    原生Ajax发送get、post请求每一步
    HTML5的web 存储localStorage、sessionStorage
    node + multer存储element-ui上传的图片
    html块级元素的水平垂、直居中的方式
    vuex之Mutation(三)
    mint ui的tabBar监听路由变化实现tabBar切换
    Vue使用better-scroll左右菜单联动
    vuex之getter(二)
  • 原文地址:https://www.cnblogs.com/mengqingjian/p/8185402.html
Copyright © 2020-2023  润新知