python - 未在 Tornado 中设置 Content-Type header

标签 python tornado

我有以下基类:

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)

一切都非常简单,除了 Content-Type 没有设置。请注意,任何其他 header 都已正确设置。

Firefox developer tools

这是怎么回事?

最佳答案

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

请注意,您实际上不需要显式设置 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()).

关于python - 未在 Tornado 中设置 Content-Type header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30610934/

相关文章:

python - 使用 python 和 tweepy 的 twitter "friends"的完整列表

python - 动态删除 Dataframe 行

Python字典检查键是否存在

javascript - Tornado、Django 和推送通知

python - Tornado 安装问题

python - 如何将此列表排序函数从 Python 2 转换为 Python 3

python - Matplotlib FuncAnimation 慢

python - 如何使用 Tornado 运行 Flask 应用程序

python - 如何在 Tornado 中删除请求?

Python Tornado 使用协程并行请求并处理异常