Python Spyne - 为SOAP响应设置不同的mimetype

时间:2013-09-17 09:05:07

标签: python mime-types content-type spyne

我的spyne SOAP服务器正在运行,它运行得非常好,但我遇到的唯一问题是我需要返回一个具有特定mimetype的响应。

我的返回内容类型是

text/html; charset=utf-8

我需要返回

text/xml; charset=utf-8

我尝试以这种方式覆盖Soap11:

class CustomSoap11(Soap11):
    mime_type = 'text/xml; charset=utf-8'

但它并没有影响返回的内容类型。

我也试过覆盖DjangoServer方法,但它也没有用。

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我必须覆盖handle_rpc函数才能设置正确的标头。默认情况下,HttpResponse返回它的默认值,所以我不得不重写DjangoServer并通过创建自定义django服务器和自定义spyneview将其包含在SpyneView中

# coding: utf-8

import logging
from django.http.response import HttpResponse, StreamingHttpResponse
from spyne.server.django import SpyneView
from spyne.application import get_fault_string_from_exception
from spyne.model.fault import Fault
from spyne.protocol.http import HttpRpc
from spyne.server.django import DjangoServer
from bluealert.notifications.sms.server import application


logger = logging.getLogger(__name__)


class CustomDjangoServer(DjangoServer):
    """ Musimy nadpisać metodę handle_rpc w DjangoServer, bo HttpResponse 
        zwraca niewłaściwy content_type."""


    def handle_rpc(self, request, *args, **kwargs):
        """Handle rpc request.

        :params request: Django HttpRequest instance.
        :returns: HttpResponse instance.
        """
        contexts = self.get_contexts(request)
        p_ctx, others = contexts[0], contexts[1:]

        if p_ctx.in_error:
            return self.handle_error(p_ctx, others, p_ctx.in_error)

        self.get_in_object(p_ctx)
        if p_ctx.in_error:
            logger.error(p_ctx.in_error)
            return self.handle_error(p_ctx, others, p_ctx.in_error)

        self.get_out_object(p_ctx)
        if p_ctx.out_error:
            return self.handle_error(p_ctx, others, p_ctx.out_error)

        try:
            self.get_out_string(p_ctx)

        except Exception, e:
            logger.exception(e)
            p_ctx.out_error = Fault('Server',
                                    get_fault_string_from_exception(e))
            return self.handle_error(p_ctx, others, p_ctx.out_error)

        have_protocol_headers = (isinstance(p_ctx.out_protocol, HttpRpc) and
                                 p_ctx.out_header_doc is not None)

        if have_protocol_headers:
            p_ctx.transport.resp_headers.update(p_ctx.out_header_doc)

        if p_ctx.descriptor and p_ctx.descriptor.mtom:
            raise NotImplementedError

        if self.chunked:
            response = StreamingHttpResponse(p_ctx.out_string)
        else:
            return HttpResponse(''.join(p_ctx.out_string), content_type="text/xml; charset=utf-8")

        p_ctx.close()
        return self.response(response, p_ctx, others)

# Zmodyfikowany widok dla spyne tak, aby przyjmował argument server 
CustomSpyneView = SpyneView
CustomSpyneView.server = CustomDjangoServer(app=application)