2010-09-23 20 views
0

Avoir un code inspiré de http://code.djangoproject.com/wiki/XML-RPC:Comment obtenir IP lors de l'utilisation SimpleXMLRPCDispatcher dans Django

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') 

Comment pourrait obtenir l'adresse IP du client dans la définition de « post_log »? J'ai vu IP address of client in Python SimpleXMLRPCServer? mais je ne peux pas l'appliquer à mon cas.

Merci.

Répondre

0

Ok je pouvais le faire ... avec quelques conseils astucieux ...

D'abord, je crée ma propre copie de SimpleXMLRPCDispatcher qui hérite tout de lui et overides 2 méthodes:

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) 

Ensuite, dans mon code, tout à faire est:

# ... 
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] 

C'est tout. Je sais que ce n'est pas très propre ... Toute suggestion pour une solution plus propre est la bienvenue!