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 源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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‘

1
2
3
4
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有区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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对象只有在请求的处理环境中才能被调用。

给个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/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处理函数被调用之后调用。即使之前的处理函数发生异常,也会调用吗,适合异常处理。

 

posted @   yihailin  阅读(241)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
点击右上角即可分享
微信分享提示