Flask源码阅读(九)——响应

12 篇文章 0 订阅

1.Flask调用视图函数后,会将其返回值作为响应内容。如果不想返回由1个,2个或者多个值组成的元组,Flask视图函数还可以返回Response对象。make_response()函数可接受1个,2个或者着多个参数,并返回一个Response对象。

2.源码

def make_response(self, rv):
        """Converts the return value from a view function to a real
        response object that is an instance of :attr:`response_class`.

        The following types are allowd for `rv`:

        ======================= ===========================================
        :attr:`response_class`  the object is returned unchanged
        :class:`str`            a response object is created with the
                                string as body
        :class:`unicode`        a response object is created with the
                                string encoded to utf-8 as body
        :class:`tuple`          the response object is created with the
                                contents of the tuple as arguments
        a WSGI function         the function is called as WSGI application
                                and buffered as response object
        ======================= ===========================================

        :param rv: the return value from the view function
        """
        if isinstance(rv, self.response_class):
            return rv
        if isinstance(rv, basestring):
            return self.response_class(rv)
        if isinstance(rv, tuple):
            return self.response_class(*rv)
        return self.response_class.force_type(rv, request.environ)

rv是视图函数的返回值。
isinstance()是python内建函数,用来判断类的继承关系。
三个if语句分别判断rv是否继承response_class,basestring,tuple(元组),分别返回rv,response_class中的rv。最后该函数将从视图函数的返回值转换为真正的,一个实例的响应对象。
basestring是str和unicode的超类(父类),也是抽象类,因此不能被调用和实例化,但可以被用来判断一个对象是否为str或者unicode的实例,isinstance(obj, basestring)等价于isinstance(obj, (str, unicode));
response_class的源码:


    #: the class that is used for response objects.  See
    #: :class:`~flask.Response` for more information.
    response_class = Response

Response来源

class Response(ResponseBase):
    """The response object that is used by default in flask.  Works like the response object from Werkzeug but is set to have a HTML mimetype by default.  Quite often you don't have to create this object yourself because:meth:`~flask.Flask.make_response` will take care of that for you.

    If you want to replace the response object used you can subclass this and set :attr:`~flask.Flask.request_class` to your subclass.
    """
    default_mimetype = 'text/html'

在flask中,相应对象是默认被使用的。工作,比如源自于WERKZEUG的响应对象,但在默认情况下设置一个HTML的MIME类型。很多时候,您不必自己创建这个对象,因为:meth:〜flask.Flask.make_response会为你保管好。
如果您想更换已经使用的相应对象,那么可以继承这一点并且设置属性
attr:~flask.Flask.request_class到您的子类。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值