0

有一个来自http://code.djangoproject.com/wiki/XML-RPC的代码:

from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.http import HttpResponse

dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5

def rpc_handler(request):
    """
    the actual handler:
    if you setup your urls.py properly, all calls to the xml-rpc service
    should be routed through here.
    If post data is defined, it assumes it's XML-RPC and tries to process as such
    Empty post assumes you're viewing from a browser and tells you about the service.
    """

    if len(request.POST):
        response = HttpResponse(mimetype="application/xml")
        response.write(dispatcher._marshaled_dispatch(request.raw_post_data))
    else:
        pass # Not interesting
    response['Content-length'] = str(len(response.content))
    return response

def post_log(message = "", tags = []):
    """ Code called via RPC. Want to know here the remote IP (or hostname). """
    pass

dispatcher.register_function(post_log, 'post_log')

如何在“post_log”定义中获取客户端的 IP 地址?我在 Python SimpleXMLRPCServer 中看到了客户端的 IP 地址?但不能将其应用于我的案例。

谢谢。

4

1 回答 1

0

好的,我可以做到...有一些漂亮的技巧...

首先,我创建了自己的 SimpleXMLRPCDispatcher 副本,它继承了它的所有内容并覆盖了 2 个方法:

class MySimpleXMLRPCDispatcher (SimpleXMLRPCDispatcher) :
    def _marshaled_dispatch(self, data, dispatch_method = None, request = None):
        # copy and paste from /usr/lib/python2.6/SimpleXMLRPCServer.py except
        response = self._dispatch(method, params)
        # which becomes
        response = self._dispatch(method, params, request)

    def _dispatch(self, method, params, request = None):
        # copy and paste from /usr/lib/python2.6/SimpleXMLRPCServer.py except
        return func(*params)
        # which becomes
        return func(request, *params)

然后在我的代码中,要做的就是:

# ...
if len(request.POST):
    response = HttpResponse(mimetype="application/xml")
    response.write(dispatcher._marshaled_dispatch(request.raw_post_data, request = request))
# ...
def post_log(request, message = "", tags = []):
    """ Code called via RPC. Want to know here the remote IP (or hostname). """
    ip = request.META["REMOTE_ADDR"]
    hostname = socket.gethostbyaddr(ip)[0]

而已。我知道它不是很干净......欢迎任何关于更清洁解决方案的建议!

于 2010-10-05T14:05:20.307 回答