如何使视图函数支持直接返回自定义的响应类?

来源:1-2 课程更新维护说明

Rethink

2021-04-16

老师好,我这边重写了一下flask.Response提供的类方法,想在接口中可以直接返回我自定义的响应类,但是为啥不生效嘞?
代码如下:

from flask import Response as _Response
from flask import Flask

class Response(_Response):
    default_status = 200
    default_mimetype = 'application/json'

    def __init__(self, response, **kwargs):
        if 'mimetype' not in kwargs and 'contenttype' not in kwargs:
            if response.startswith('<?xml'):
                kwargs['mimetype'] = 'application/xml'

        return super(Response, self).__init__(response, **kwargs)

	# 重写的这个类方法没有生效
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, McResponse):
            r = response.response
        return super(Response, cls).force_type(r, environ)
        
class Flask(_Flask):
    json_encoder = JSONEncoder
    response_class = Response
  
def create_app(config_name=None):
	app = Flask(__name__)
	....
	return app

我想在试图函数中直接返回McResponse对象时,会有问题:
TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a McResponse. // Werkzeug Debugger

想问下老师,为什么没有生效呢?

写回答

1回答

Rethink

提问者

2021-04-16

调试的时候 发现根本没有进入到这个force_type方法

ps: McResponse自定义的响应类没有基类,

0
0

Python Flask高级编程之RESTFul API前后端分离精讲

RESTFul+权限管理+token令牌+扩展flask=提升编程思维

2052 学习 · 359 问题

查看课程