zoukankan      html  css  js  c++  java
  • Flask 初印象

    Flask 出生于2010年,集中了其他python web框架的长处,定位于微小项目上。

    特点

    1 内置开发服务器和调试器

    2 于Python单元测试功能无缝衔接

      Flask框架提供了一个与Python自带的单元测试框架unitest无缝衔接的测试接口,

      即Flask对象的test_client函数,测试程序可以模拟进行HTTP访问的客户端来调用

           Flask路由处理函数,并且获取函数的输出来进行自定义的验证。

    3 使用Jinja2模板

    4 完全兼容WSGI 1.0标准

    5 基于Unicode 编码

      默认情况下,Flask框架自动添加一个UTF-8编码格式的HTTP Head。

    环境搭建

    1 安装Flask

    pip install Flask

    2 安装SQLALchemy

    pip install SQLAlchemy

    3 安装Flask-WTForm

    WTForm 是一个简化HTML表单处理的Python库,而Flask-WTForm提供了

    对它的简单封装

    pip install Flask-WTF

    Hello World 入门

    #!/usr/bin/env python
    # coding: utf-8
    
    
    from flask import Flask
    app = Flask(__name__)
    
    @app.route('/')
    def hello_world():
        return 'Hello, World!'
    
    if __name__ == '__main__':
        app.run()

    这里说一下Flask框架的特色:

    1 app = Flask(__name__) 

    这是实例化了一个Flask类的实例,作用:把应用模块或包的名字传给Flask构造函数的第一个参数,

    Flask在运行过程中将使用这个参数作为定位模板和其他静态文件的基础

    2 route 装饰器

    以下是Flask 源码

    In [7]: Flask.route??
    Signature: Flask.route(self, rule, **options)
    Source:
        def route(self, rule, **options):
            """A decorator that is used to register a view function for a
            given URL rule.  This does the same thing as :meth:`add_url_rule`
            but is intended for decorator usage::
    
                @app.route('/')
                def index():
                    return 'Hello World'
    
            For more information refer to :ref:`url-route-registrations`.
    
            :param rule: the URL rule as string
            :param endpoint: the endpoint for the registered URL rule.  Flask
                             itself assumes the name of the view function as
                             endpoint
            :param options: the options to be forwarded to the underlying
                            :class:`~werkzeug.routing.Rule` object.  A change
                            to Werkzeug is handling of method options.  methods
                            is a list of methods this rule should be limited
                            to (`GET`, `POST` etc.).  By default a rule
                            just listens for `GET` (and implicitly `HEAD`).
                            Starting with Flask 0.6, `OPTIONS` is implicitly
                            added and handled by the standard request handling.
            """
            def decorator(f):
                endpoint = options.pop('endpoint', None)
                self.add_url_rule(rule, endpoint, f, **options)
                return f
            return decorator
    

     通过装饰器,我们将路由和其相应的处理函数绑定在一起。除了直接传url作为第一个参数,我们还能通过methods参数,绑定更多的访问方式。

    如 @app.route('/thisisurl',methods=['POST'])。通过阅读route的docstring‘

     By default a rule
                            just listens for `GET` (and implicitly `HEAD`).
                            Starting with Flask 0.6, `OPTIONS` is implicitly
                            added and handled by the standard request handling.

    我们可以知道 当GET方式指定时,HEAD方式也被追加到该装饰器中;Flask 0.6以后的版本,options访问方式被追加到所有装饰器。

     

    其他特性

    1 路由反向生成

      Flask 提供了flask.url_for()函数获取http请求函数通过app.route绑定的url。

    2 Context上下文

      web编程中将服务器端获得应用及请求相关信息的对象称作上下文

    2.1 会话上下文

      会话上下文是Web服务器上基于Cookie的对象,它提供了同一个客户端在多次请求之间共享信息的方式

    Flask框架通过flask.session对象操作会话。这是要特别说一下,flask的会话是通过Cookie实现的,这是的session和web前端一个标签就是

    一个session有区别。

    class LocalProxy(__builtin__.object)
     |  Acts as a proxy for a werkzeug local.  Forwards all operations to
     |  a proxied object.  The only operations not supported for forwarding
     |  are right handed operands and any kind of assignment.
     |  
     |  Example usage::
     |  
     |      from werkzeug.local import Local
     |      l = Local()
     |  
     |      # these are proxies
     |      request = l('request')
     |      user = l('user')
     |  
     |  
     |      from werkzeug.local import LocalStack
     |      _response_local = LocalStack()
     |  
     |      # this is a proxy
     |      response = _response_local()
     |  
     |  Whenever something is bound to l.user / l.request the proxy objects
     |  will forward all operations.  If no object is bound a :exc:`RuntimeError`
     |  will be raised.
     |  
     |  To create proxies to :class:`Local` or :class:`LocalStack` objects,
     |  call the object as shown above.  If you want to have a proxy to an
     |  object looked up by a function, you can (as of Werkzeug 0.6.1) pass
     |  a function to the :class:`LocalProxy` constructor::
     |  
     |      session = LocalProxy(lambda: get_current_request().session)
     |  
     |  .. versionchanged:: 0.6.1
     |     The class can be instanciated with a callable as well now.
     |  
    

      以上是help(flask.session)的说明,这里Flask框架采用特别机制,使得flask.session对象只有在请求的处理环境中才能被调用。

    给个例子:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    
    from flask import Flask, session
    from datetime import datetime
    
    app = Flask(__name__)
    
    app.secret_key = 'SET_ME_BEFORE_USE_SESSION'
    
    @app.route('/write_session')
    def writeSession():
        session['key_time']= datetime.now().strftime('%Y-%m-%d %H:%M:%S')		#将当前时间保存在Session中
        return session['key_time']  			#返回当前时间
     
    @app.route('/read_session')
    def readSession():
        return session.get('key_time')			#获得上次调用writeSession时写入的时间,并返回
    
    if __name__ == '__main__':
        app.run()

    2.2 应用全局对象

      应用全局对象提供了在一次请求的多个处理函数中共享信息的方式。在Flask中每个请求可能会触发多个相应函数,而如果想在多个响应

      函数之间共享数据,则需要用到应用全局对象(Application Global)。应用全局对象是Flask为每个请求自动建立的一个对象。相对于简单的

      全局对象,应用全局对象可以保证线程安全。

      flask框架使用flask.g实现上述功能。

    2.3 请求上下文

      是web服务器管理单次用户请求的环境对象,用于处理客户端向Web服务器发送的数据。请求上下文主要是在服务器端获得从客户端提交的

      数据。这些数据包括:URL参数,Form表单数据,Cookie,HTML头信息,URL等。flask框架通过Request对象实现。

    2.4 回调接入点

      Flask提供了before_request,after_request,teardown_request等装饰器,为所有flask app实例的handler提供共同的处理逻辑。

      before_request:每个请求都会在被处理之前先执行本接入点,可定义多个before_request。一旦一个before_request返回Response,则对应的url

      处理函数不会调用,flask直接将Response返回给客户端。

      after_request:在每个请求的URL处理函数被调用之后调用本接入点

      teardown_request:在每个请求的URL处理函数被调用之后调用。即使之前的处理函数发生异常,也会调用吗,适合异常处理。

     

  • 相关阅读:
    Java锁到底锁的到底是哪个对象?什么是锁对象
    什么是正向代理,什么是反向代理
    到底什么是线程安全
    为什么要使用接口,直接写是实现类不行吗
    Nginx配置学习(一)
    Zookeeper集群节点数量为什么要是奇数个?
    Redis 5 单实例数据迁移到Cluster
    Centos8安装Nginx1.18.0
    vmware workstation15 桥接模式互ping不通,虚机可以连通局域网其他机器解决方法
    MongoDB double类型保留2位小数
  • 原文地址:https://www.cnblogs.com/linyihai/p/7361179.html
Copyright © 2011-2022 走看看