0

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

我返回的 Content-Type 是

text/html; charset=utf-8

我需要返回

text/xml; charset=utf-8

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

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

但它不影响返回的内容类型。

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

有什么建议么?

4

1 回答 1

0

我必须重写我的 handle_rpc 函数来设置正确的标题。默认情况下 HttpResponse 返回它的默认值,所以我必须通过创建自定义 django 服务器和自定义 spyneview 来覆盖 DjangoServer 并将其包含在 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)
于 2013-09-17T11:00:52.947 回答