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
到您的子类。