在Tornad中未设置内容类型头

2024-05-19 23:02:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下基类:

class CorsHandler(tornado.web.RequestHandler):

    def set_default_headers(self):
        super(CorsHandler, self).set_default_headers()

        self.set_header('Access-Control-Allow-Origin', self.request.headers.get('Origin', '*'))
        self.set_header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
        self.set_header('Access-Control-Allow-Credentials', 'true')
        self.set_header('Access-Control-Allow-Headers', ','.join(
            self.request.headers.get('Access-Control-Request-Headers', '').split(',') +
            ['Content-Type']
        ))

        self.set_header('Content-Type', 'application/json')

    def options(self, *args, **kwargs):
        pass

以及以下处理程序:

def get(self, resource_id=None, field=None):
    try:
        if resource_id is None:
            response = self.resource.query.filter_by(is_deleted=False).all()

        else:
            record = self.resource.query.get(int(resource_id))

            if field is None:
                response = record
            else:
                response = {field: getattr(record, field)}

        self.db.session.commit()

    except Exception, e:
        self.db.session.rollback()

        self.send_error(500, message=e.message)

    self.write(response)

一切都很简单,除了内容类型没有设置。请注意,其他任何标题都已正确设置。

Firefox developer tools

怎么了?


Tags: selfnoneidfieldgetaccessisresponse
1条回答
网友
1楼 · 发布于 2024-05-19 23:02:19

这似乎是一个304 Not Modified响应。请记住,只有第一个200 OK响应包含Content-Type头。如果您请求相同的资源,则以下响应将忽略此头。

注意,实际上不需要显式设置Content-Type。如果您查看Tornado的源代码,可以在write(self, chunk)的注释中找到:

If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).

相关问题 更多 >