我必须重写我的 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)