def post(self, request): dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) dispatcher.register_function(partial(self.ping, request), 'pingback:ping') response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) return response
class WSGIXMLRPCApplication(object): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=[]): """Create windmill xmlrpc dispatcher""" self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def handler(self, environ, start_response): """XMLRPC service for windmill browser core to communicate with""" if environ['REQUEST_METHOD'] == 'POST': return self.handle_POST(environ, start_response) else: start_response("400 Bad request", [('Content-Type', 'text/plain')]) return [''] def handle_POST(self, environ, start_response): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: # Get arguments by reading body of request. # We read this in chunks to avoid straining length = int(environ['CONTENT_LENGTH']) data = environ['wsgi.input'].read(length) # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error start_response("500 Server error", [('Content-Type', 'text/plain')]) return [] else: # got a valid XML RPC response start_response("200 OK", [('Content-Type', 'text/xml'), ('Content-Length', str(len(response)),)]) return [response] def __call__(self, environ, start_response): return self.handler(environ, start_response)
class WSGIXMLRPCApplication(object): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=()): """Create windmill xmlrpc dispatcher""" try: self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) except TypeError: # python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() @Request.application def handler(self, request): if request.method == 'POST': return self.handle_POST(request) else: return BadRequest() def handle_POST(self, request): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: # Read the data from the request data = request.get_data() # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None)) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error return InternalServerError() else: # got a valid XML RPC response return Response(response, mimetype='text/xml') def __call__(self, environ, start_response): return self.handler(environ, start_response)
def handler(request, response, methods): response.session_id = None # no sessions for xmlrpc dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) for method in methods: dispatcher.register_function(method) dispatcher.register_introspection_functions() response.headers['Content-Type'] = 'text/xml' dispatch = getattr(dispatcher, '_dispatch', None) return dispatcher._marshaled_dispatch(request.body.read(), dispatch)
def get_handler(methodlist): dispatcher = SimpleXMLRPCDispatcher(False, None) for method in web.group(methodlist, 2): dispatcher.register_function(method[1], method[0]) class rpc: def GET(self): web.header('Content-Type', 'text/html') print get_doc(dispatcher) def POST(self): response = dispatcher._marshaled_dispatch(web.webapi.data()) web.header('Content-Type', 'text/xml') web.header('Content-length', str(len(response))) print response return rpc
def register_function(self, function, name=None): """ This will register the given function. There are two ways to use it. As a plain old method, with or without a name:: handler.register_function(spam) handler.register_function(spam, 'spam') As a decorator, also with or without a name:: @handler.register_function def spam(): pass @handler.register_function('spam') def spam(): pass It's shorter and easier to use :meth:`register`, however, as it does the exact same thing. :param function: The function to register. (In the named decorator form, this is the function's name.) :param name: The name to use, except in the named decorator form. If not given, the function's :obj:`__name__` attribute will be used. """ if isinstance(function, basestring): return lambda fn: self.register_function(fn, function) return Dispatcher.register_function(self, function, name)
class ServerGateway(object): def __init__(self, prefix): self.prefix = prefix try: # Python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() except TypeError: # Python 2.5 self.dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) def add_function(self, name, func): self.dispatcher.register_function(func, ".".join([self.prefix, name])) def connect( self, func=None, name=None): def _connector(func): self.add_function(not name and func.__name__ or name, func) return func if not func: return _connector else: _connector(func) return func def __call__(self, request, *args, **kwargs): if kwargs: raise RuntimeError("Xmlrpc server gateway cannot handle key variable argumets") def custom_dispatch(method, params): return self.dispatcher._dispatch(method, params + tuple(args)) response = HttpResponse() if len(request.POST): response.write(self.dispatcher._marshaled_dispatch(request.raw_post_data, custom_dispatch)) else: methods = self.dispatcher.system_listMethods() response['Content-Type'] = 'text/plain' for method in methods: # __doc__ help = self.dispatcher.system_methodHelp(method) response.write("%s:\n %s\n\n" % (method, help)) response['Content-Length'] = str(len(response.content)) return response
class XMLRPCApplication(RestApplication): """Application to handle requests to the XMLRPC service""" def __init__(self, instance=None, methods=[]): """Create windmill xmlrpc dispatcher""" try: self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) except TypeError: # python 2.4 self.dispatcher = SimpleXMLRPCDispatcher() if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def POST(self, request, *path): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ try: data = str(request.body) # In previous versions of SimpleXMLRPCServer, _dispatch # could be overridden in this class, instead of in # SimpleXMLRPCDispatcher. To maintain backwards compatibility, # check to see if a subclass implements _dispatch and # using that method if present. response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) response += '\n' except: # This should only happen if the module is buggy # internal error, report as HTTP server error return Response500() else: # got a valid XML RPC response return XMLResponse(response)
class XmlRpc(object): def __init__(self, encoding=None, allow_none=True, use_datetime=0): self.__queue = [] self.__encoding = encoding self.__allow_none = allow_none self.__use_datetime = use_datetime self.__dispatcher = SimpleXMLRPCDispatcher(allow_none=allow_none, encoding=encoding) def splitfmt(self): return "xml" def initiate_request(self, method, args, kwargs, completion): if kwargs: raise NotImplemented("Keyword arguments not supported in XML-RPC mode") self.__queue.append(completion) return xmlrpc_dumps(args, method, encoding=self.__encoding, allow_none=self.__allow_none) def handle_response(self, rstr): completion = self.__queue.pop(0) try: response = xmlrpc_loads(rstr, self.__use_datetime) completion(response[0][0], None) except Fault as f: completion(None, f) def dispatch_request(self, reqstr): p,m = xmlrpc_loads(reqstr, self.__use_datetime) try: rsp = self.__dispatcher._dispatch(m, p) response = xmlrpc_dumps((rsp,), allow_none=self.__allow_none, encoding=self.__encoding) except Fault as fault: response = xmlrpc_dumps(fault, allow_none=self.__allow_none, encoding=self.__encoding) except: exc_type, exc_value, exc_tb = sys.exc_info() response = xmlrpc_dumps( Fault(1, "%s:%s" % (exc_type, exc_value)), encoding=self.__encoding, allow_none=self.__allow_none) return response def register_function(self, func, name=None): self.__dispatcher.register_function(func, name)
class WSGIXMLRPCApplication: def __init__(self,instance=None,methods=[]): self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True,encoding=None) if instance is not None: self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() def __call__(self,environ,start_response): if environ["REQUEST_METHOD"] == "POST": return self.handle_post(environ,start_response) else: start_response("400 Bad request",[("Content-Type","text/plain")]) return [''] def handle_post(self,environ,start_response): try: max_chunk_size = 10*1024*1024 size_remaining = int(environ["CONTENT_LENGTH"]) L = [] rfile = environ['wsgi.input'] while size_remaining: chunk_size = min(size_remaining, max_chunk_size) chunk = rfile.read(chunk_size) if not chunk: break L.append(chunk) size_remaining -= len(L[-1]) data = ''.join(L) data = self.decode_request_content(data,environ,start_response) if isinstance(data, list): return data response = self.dispatcher._marshaled_dispatch(data) except Exception, e: start_response("%d %s" % (500,_RESPONSE_STATUSES[500]),[ ("Content-length", '') ]) return [] else:
class XMLRPCDispatcher(Resource): '''A Resource that knows how to host an XMLRPCObject and serve it''' def __init__(self, application, request, response, session, instance=None, methods=[], allow_none=True, encoding=None): '''initializes this dispatcher which can handle XMLRPC requests.''' if not instance: raise ValueError("You must pass in a non-null object which we will serve") super(XMLRPCDispatcher, self).__init__(application, request, response, session) self.dispatcher = SimpleXMLRPCDispatcher(allow_none=allow_none, encoding=encoding) self.dispatcher.register_instance(instance) for method in methods: self.dispatcher.register_function(method) self.dispatcher.register_introspection_functions() self.dispatcher.register_multicall_functions() @POST @Route("/{path:.*}") def post(self, path): ''' Attempts to process all posts as XMLRPC Requests which are then dispatched to the XMLRPCObject. Most of the code was taken from SimpleXMLRPCServer with modifications to make it compatible with Gates ''' try: data = self.request.body response = self.dispatcher._marshaled_dispatch( data, getattr(self.dispatcher, '_dispatch', None) ) except Exception as e: # This should only happen if the module is buggy # internal error, report as Internal HTTP Server error traceback.print_exc(e) abort(500, "XMLRPC Application Error! You shouldn't be seeing this. We're sorry.") else: # We got a valid XML RPC response self.response.type = "text/xml" self.response.write(response)
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. """ #moving this here to see if it will fix the thread leaks dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) # Python 2.5 if len(request.POST): dispatcher.register_function(_updateStatus, 'updateStatus') dispatcher.register_function(_setSceneError, 'setSceneError') dispatcher.register_function(_set_scene_unavailable, 'setSceneUnavailable') dispatcher.register_function(_markSceneComplete, 'markSceneComplete') dispatcher.register_function(_getConfiguration, 'getConfiguration') dispatcher.register_function(_getScenesToProcess, 'getScenesToProcess') dispatcher.register_function(_getScenesToPurge, 'getScenesToPurge') dispatcher.register_function(_getSceneInputPath, 'getSceneInputPath') dispatcher.register_function(_getDataSourceCredentials, 'getDataSourceCredentials') #if our leak isn't fixed, try checking to see if we need to close the response here. response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: # right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') response['Content-length'] = str(len(response.content)) return response
query_filter = None for field, values in spec.items(): for value in values: if field not in field_map: continue field_filter = Q(**{field_map[field]: value}) if not query_filter: query_filter = field_filter continue if operator == 'and': query_filter &= field_filter else: query_filter |= field_filter result = [] packages = models.Package.objects.filter(query_filter).all()[:20] for package in packages: release = package.releases.all()[0] result.append({ 'name': package.name, 'summary': release.summary, 'version': release.version, '_pypi_ordering': 0, }) return result dispatcher.register_function(search, 'search')
return False registrations = { 'whatis_ip': whatis_ip, 'whois_ip': whois_ip, 'whoami': whoami, 'ping': ping, 'usage': usage, 'usage_history': usage_history, 'coffee_ip': coffee_ip, 'r_disown_mac': r_disown_mac, } for k in registrations: dispatcher.register_function(registrations[k], k) # converts a datetime object to an integer with seconds since the unix epoch class JSONDateTimeEncoder(json.JSONEncoder): def default(self, o=datetime): return mktime(o.timetuple()) def httpget_handler(request, output_format, method): # this handles requests through our "simple" api handler. # this outputs in a few formats. output_format = output_format.lower() supported_formats = ['json', 'pickle', 'csv', 'python'] if output_format not in supported_formats: raise Exception, "Unsupported output format"
# response.write("The following methods are available:<ul>") # methods = server.system_listMethods() # # for method in methods: # # right now, my version of SimpleXMLRPCDispatcher always # # returns "signatures not supported"... :( # # but, in an ideal world it will tell users what args are expected # sig = server.system_methodSignature(method) # # # this just reads your docblock, so fill it in! ## help = server.system_methodHelp(method) # help = '' # # response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) # # response.write("</ul>") # response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') # # response['Content-length'] = str(len(response.content)) return response server = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) server.register_introspection_functions() def ping(name, site_url, entry_url, rss_url): logging.info('ping %s %s %s %s' % (name, site_url, entry_url, rss_url)) return 'ping %s %s %s %s' % (name, site_url, entry_url, rss_url) server.register_function(ping, 'weblogUpdates.ping')
for method in methods: # right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response['Content-length'] = str(len(response.content)) return response def multiply(a, b): """ Multiplication is fun! Takes two arguments, which are multiplied together. Returns the result of the multiplication! """ return a*b # you have to manually register all functions that are xml-rpc-able with the dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from the XML-RPC side... dispatcher.register_function(multiply, 'multiply') dispatcher.register_function(write_info, 'writeinfo')
}) environ = { 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1', } r = WSGIRequest(environ) r.data = build_dict r.META['CONTENT_TYPE'] = 'application/json' package = unicode(info.get('package')) try: pro, created = Project.objects.get_or_create(name=package, slug=slugify(package)) except: pass ProjectBuildListHandler().create(r, package) return "Processed Correctly" def check_should_build(client_info, True, reserve_time): return (True, "We always build, now!") dispatcher.register_function(add_results, 'add_results') dispatcher.register_function(check_should_build, 'check_should_build')
if c: mb.append((m,c[0].hierarquia or 9999999)) else: mb.append((m,9999999)) mb.sort(key=lambda x: x[1]) retorno = [] for m,h in mb: membro = {'nome':m.nome, 'cargo':m.cargo_atual(), 'email':m.email, 'lattes':m.url_lattes} if m.foto: fname = '_'.join(m.nome.split()[:4]).lower() fname = re.sub('[^\w]', '', fname) membro.update({'foto':xmlrpclib.Binary(m.foto.file.read()), 'fname':fname}) retorno.append(membro) return retorno dispatcher.register_function(membros, 'membros') def termos(): """ Uma lista dos termos de outorga """ retorno = [] for t in Termo.objects.all(): retorno.append({'id':t.id, 'termo':t.__unicode__(), 'ano':t.ano}) return retorno dispatcher.register_function(termos, 'termos') def custo_acordos(termo_id, acordos):
'cargo': m.cargo_atual(), 'email': m.email, 'lattes': m.url_lattes } if m.foto: fname = '_'.join(m.nome.split()[:4]).lower() fname = re.sub('[^\w]', '', fname) membro.update({ 'foto': xmlrpclib.Binary(m.foto.file.read()), 'fname': fname }) retorno.append(membro) return retorno dispatcher.register_function(membros, 'membros') def termos(): """ Uma lista dos termos de outorga """ retorno = [] for t in Termo.objects.all(): retorno.append({'id': t.id, 'termo': t.__unicode__(), 'ano': t.ano}) return retorno dispatcher.register_function(termos, 'termos')
class WSGIXMLRPCApplication(object): """WSGI application to handle requests to the XMLRPC service. This WSGI application acts like the Python standard `SimpleXMLRPCServer` but processes WSGI requests instead and does not fiddle around with raw HTTP. The passed in `cache_dir` is used only if set. """ def __init__(self, cache_dir=None): # set up a dispatcher self.dispatcher = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) self.dispatcher.register_function(self.convert_locally, 'convert_locally') self.dispatcher.register_function(self.get_cached, 'get_cached') self.dispatcher.register_introspection_functions() self.cache_dir = cache_dir def convert_locally(self, src_path, options): """Convert document in `path`. Expects a local path to the document to convert. The `options` are a dictionary of options as accepted by all converter components in this package. The cache (if set) will be updated. Returns path of converted document, a cache key and a dictionary of metadata. The cache key is ``None`` if no cache was used. """ result_path, cache_key, metadata = convert_doc(src_path, options, self.cache_dir) return result_path, cache_key, metadata def get_cached(self, cache_key): """Get a cached document. Retrieve the document representation stored under `cache_key` in cache if it exists. Returns `None` otherwise. """ client = Client(cache_dir=self.cache_dir) return client.get_cached(cache_key) @wsgify def __call__(self, req): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. Most code taken from SimpleXMLRPCServer with modifications for wsgi and my custom dispatcher. """ if req.method != 'POST': return exc.HTTPBadRequest() try: data = req.environ['wsgi.input'].read(req.content_length) response = self.dispatcher._marshaled_dispatch( data, self.dispatcher._dispatch) + b'\n' except: # pragma: no cover # This should only happen if the module is buggy # internal error, report as HTTP server error return exc.HTTPServerError() else: # got a valid XML RPC response response = Response(response) response.content_type = 'text/xml' return response
response = HttpResponse() if len(request.POST): response = HttpResponse( mimetype="application/xml" ) # Cleaner to reinstantiate than to add seemingly useless else clause response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) elif settings.DEBUG: response.write("<b>This is an XML-RPC Service.</b><br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: <pre>%s</pre>" % (method, help)) response.write("</ul>") response['Content-length'] = str(len(response.content)) return response svc_managers = ServiceManagers(facade.managers) # Iterate through the managers dict and register methods with the xmlrpc gateway for m in svc_managers.exposed_managers: instance = svc_managers.get_manager_class(m)() methods = instance._get_method_list() for method in methods: dispatcher.register_function(getattr(instance, method), '%s.%s' % (m, method)) # vim:tabstop=4 shiftwidth=4 expandtab
contact = crm.Contact.objects.get(user__email=username) except crm.Contact.DoesNotExist: contact = None else: try: contact = crm.Contact.objects.get(user__username=username) except crm.Contact.DoesNotExist: contact = None return contact def authenticate(username, password): return bool(auth.authenticate(username=username, password=password)) dispatcher.register_function(authenticate, 'authenticate') def project_relationships(project_trac_env, username): groups = [] contact = _get_contact(username) if contact: groups = crm.RelationshipType.objects.filter( project_relationships__contact=contact, project_relationships__project__trac_environment=project_trac_env, ).values_list('slug', flat=True) return list(groups) dispatcher.register_function(project_relationships, 'project_relationships')
</params> </methodCall> """ try: colname, dbname, collection, database = get_database_info(params) options = get_xml_options(params) records = database[options.start:options.end] if options.reverse: records.reverse() result = StringIO() for field in records: result.write(field.to_xml()) return result.getvalue().encode(options.gizmo) except Exception, e: return _("** Read Record (%s)") % str(e) # you have to manually register all functions that are xml-rpc-able with the dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from the XML-RPC side... dispatcher.register_function(createDB, 'createDB') dispatcher.register_function(deleteDB, 'deleteDB') dispatcher.register_function(createRecord, 'createRecord') dispatcher.register_function(updateRecord, 'updateRecord') dispatcher.register_function(deleteRecord, 'deleteRecord') dispatcher.register_function(readRecord, 'readRecord')
class RPCDispatcher: """ Dispatches method calls to either the xmlrpc or jsonrpc dispatcher """ def __init__(self, url="", apps=[], restrict_introspection=False): version = platform.python_version_tuple() self.url = url self.rpcmethods = [] # a list of RPCMethod objects self.jsonrpcdispatcher = JSONRPCDispatcher() if int(version[0]) < 3 and int(version[1]) < 5: # this is for python 2.4 and below self.xmlrpcdispatcher = SimpleXMLRPCDispatcher() else: # python 2.5+ requires different parameters self.xmlrpcdispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) if not restrict_introspection: self.register_method(self.system_listmethods) self.register_method(self.system_methodhelp) self.register_method(self.system_methodsignature) self.register_method(self.system_describe) self.register_rpcmethods(apps) @rpcmethod(name="system.describe", signature=["struct"]) def system_describe(self): """ Returns a simple method description of the methods supported """ description = {} description["serviceType"] = "RPC4Django JSONRPC+XMLRPC" description["serviceURL"] = (self.url,) description["methods"] = [ { "name": method.name, "summary": method.help, "params": method.get_params(), "return": method.get_returnvalue(), } for method in self.rpcmethods ] return description @rpcmethod(name="system.listMethods", signature=["array"]) def system_listmethods(self): """ Returns a list of supported methods """ methods = [method.name for method in self.rpcmethods] methods.sort() return methods @rpcmethod(name="system.methodHelp", signature=["string", "string"]) def system_methodhelp(self, method_name): """ Returns documentation for a specified method """ for method in self.rpcmethods: if method.name == method_name: return method.help # this differs from what implementation in SimpleXMLRPCServer does # this will report via a fault or error while SimpleXMLRPCServer # just returns an empty string raise Fault(APPLICATION_ERROR, "No method found with name: " + str(method_name)) @rpcmethod(name="system.methodSignature", signature=["array", "string"]) def system_methodsignature(self, method_name): """ Returns the signature for a specified method """ for method in self.rpcmethods: if method.name == method_name: return method.signature raise Fault(APPLICATION_ERROR, "No method found with name: " + str(method_name)) def register_rpcmethods(self, apps): """ Scans the installed apps for methods with the rpcmethod decorator Adds these methods to the list of methods callable via RPC """ for appname in apps: # check each app for any rpcmethods app = __import__(appname, globals(), locals(), ["*"]) for obj in dir(app): method = getattr(app, obj) if callable(method) and getattr(method, "is_rpcmethod", False): # if this method is callable and it has the rpcmethod # decorator, add it to the dispatcher self.register_method(method, method.external_name) def jsondispatch(self, raw_post_data): """ Sends the post data to a jsonrpc processor """ return self.jsonrpcdispatcher.dispatch(raw_post_data) def xmldispatch(self, raw_post_data): """ Sends the post data to an xmlrpc processor """ return self.xmlrpcdispatcher._marshaled_dispatch(raw_post_data) def get_method_name(self, raw_post_data, request_format="xml"): """ Gets the name of the method to be called given the post data and the format of the data """ if request_format == "xml": # xmlrpclib.loads could throw an exception, but this is fine # since _marshaled_dispatch would throw the same thing try: params, method = xmlrpclib.loads(raw_post_data) return method except Fault: return None else: try: # attempt to do a json decode on the data jsondict = json.loads(raw_post_data) if not isinstance(jsondict, dict) or "method" not in jsondict: return None else: return jsondict["method"] except ValueError: return None def list_methods(self): """ Returns a list of RPCMethod objects supported by the server """ return self.rpcmethods def register_method(self, method, name=None, signature=None, helpmsg=None): """ Registers a method with the rpc server """ meth = RPCMethod(method, name, signature, helpmsg) self.xmlrpcdispatcher.register_function(method, meth.name) self.jsonrpcdispatcher.register_function(method, meth.name) self.rpcmethods.append(meth)
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. """ d = SimpleXMLRPCDispatcher(allow_none=True, encoding=None) if len(request.body): d.register_function(_update_status, 'update_status') d.register_function(_set_product_error, 'set_scene_error') d.register_function(_set_product_unavailable, 'set_scene_unavailable') d.register_function(_mark_product_complete, 'mark_scene_complete') d.register_function(_handle_orders, 'handle_orders') d.register_function(_queue_products, 'queue_products') d.register_function(_get_configuration, 'get_configuration') d.register_function(_get_products_to_process, 'get_scenes_to_process') response = HttpResponse(content_type="application/xml") response.write(d._marshaled_dispatch(request.body)) else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = d.system_listMethods() for method in methods: sig = d.system_methodSignature(method) # this just reads your docblock, so fill it in! help_msg = d.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help_msg)) response.write("</ul>") response['Content-length'] = str(len(response.content)) return response
response.write( xmlrpcdispatcher._marshaled_dispatch(request.raw_post_data)) if settings.DEBUG: print response return response except Exception, e: return HttpResponseServerError() else: return render_to_response(settings.XMLRPC_GET_TEMPLATE) # Load up any methods that have been registered with the server in settings for path, name in settings.XMLRPC_METHODS: # if "path" is actually a function, just add it without fuss if callable(path): xmlrpcdispatcher.register_function(path, name) continue # Otherwise we try and find something that we can call i = path.rfind('.') module, attr = path[:i], path[i + 1:] try: mod = __import__(module, globals(), locals(), [attr]) except ImportError, e: raise ImproperlyConfigured, "Error registering XML-RPC method: " \ + "module %s can't be imported" % module try: func = getattr(mod, attr) except AttributeError:
from django.contrib.sessions.backends.db import Session try: Session.objects.get(session_key=token) return True except Session.DoesNotExist: return False def login(username, password): ''' params (username, password) ''' from django.contrib.sessions.backends.db import SessionStore user = auth.authenticate(identification=username, password=password) # import pdb; pdb.set_trace() if user: session = SessionStore() session['user_id'] = user.id session.save() response = session.session_key else: response = 'username or password is wrong' return response dispatcher.register_instance(Services()) dispatcher.register_function(login) dispatcher.register_function(token_is_valid) #dispatcher.register_function(get_notifications_by_id) #dispatcher.register_function(get_notifications_by_date) #dispatcher.register_function(get_notifications_by_location) #dispatcher.register_function(register_to_app)
else: submit.State = unicode(JudgeRes[3][0]) submit.Src = JudgeRes[3][0] submit.Detail = JudgeRes submit.isWait = False submit.save() return True def RPC_GetDataURL(jk, name): if jk != JudgeKey: return False try: Prob = Problem.objects.get(Name=name) except Problem.DoesNotExist: return False if not Prob.Data: return False return [ MD5File(Prob.Data), DataServer + reverse("DataDownland", kwargs={"name": name}) + "?JudgeKey=" + JudgeKey ] XmlRPC = SimpleXMLRPCDispatcher(allow_none=True) XmlRPC.register_function(RPC_GetSubmit, "GetSubmit") XmlRPC.register_function(RPC_PostRes, "PostRes") XmlRPC.register_function(RPC_AddSubmit, "AddSubmit") XmlRPC.register_function(RPC_GetDataURL, "GetDataURL")
from django.http import HttpResponse, HttpResponseNotAllowed from django.views.decorators.csrf import csrf_exempt from SimpleXMLRPCServer import SimpleXMLRPCDispatcher dispatcher = SimpleXMLRPCDispatcher() logger = logging.getLogger("django.request") @csrf_exempt def xmlrpc_handler(request, service=None): if request.method == "POST": # logger.debug('%s\n\n\n', request.body) response = HttpResponse(mimetype="application/xml") response.write(dispatcher._marshaled_dispatch(request.body)) response["Content-length"] = str(len(response.content)) return response else: return HttpResponseNotAllowed(["POST"]) from empressx.retinue.methods import app, web dispatcher.register_function(app.serve, "app.serve") dispatcher.register_function(app.unserve, "app.unserve") dispatcher.register_function(app.reserve, "app.reserve") dispatcher.register_function(web.serve, "web.serve") dispatcher.register_function(web.unserve, "web.unserve")
try: func, smth, params = resolver.resolve(path) except ur.Resolver404: return PingbackError.TARGET_DOES_NOT_EXIST name = resolver.reverse_dict[func][-1].name if not name in settings.PINGBACK_SERVER: return PingbackError.TARGET_IS_NOT_PINGABLE getter = settings.PINGBACK_SERVER[name] if not callable(getter): getter = get_callable(getter) obj = getter(**params) ctype = ContentType.objects.get_for_model(obj) try: Pingback.objects.get(url=source, content_type=ctype, object_id=obj.id) return PingbackError.PINGBACK_ALREADY_REGISTERED except Pingback.DoesNotExist: pass pb = Pingback(object=obj, url=source, content=content.encode('utf-8'), title=title.encode('utf-8'), approved=True) pb.save() return 'pingback from %s to %s saved' % (source, target) dispatcher.register_function(ping, 'pingback.ping')
try: response.write( xmlrpcdispatcher._marshaled_dispatch(request.raw_post_data)) if settings.DEBUG: print response return response except Exception, e: return HttpResponseServerError() else: return render_to_response(settings.XMLRPC_GET_TEMPLATE) # Load up any methods that have been registered with the server in settings for path, name in settings.XMLRPC_METHODS: # if "path" is actually a function, just add it without fuss if callable(path): xmlrpcdispatcher.register_function(path, name) continue # Otherwise we try and find something that we can call i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = __import__(module, globals(), locals(), [attr]) except ImportError, e: raise ImproperlyConfigured, "Error registering XML-RPC method: " \ + "module %s can't be imported" % module try: func = getattr(mod, attr) except AttributeError:
} def mock_ping(sourceURI, targetURI): response = mock_responses.get((sourceURI, targetURI), Fault(0, 'Error')) if isinstance(response, Fault): raise response return response try: dispatcher = SimpleXMLRPCDispatcher() except TypeError: dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) dispatcher.register_function(mock_ping, "pingback.ping") def mock_pingback_server(request): if not request.method == 'POST': return HttpResponseNotAllowed(['POST']) response = HttpResponse(mimetype='text/xml') response.write(dispatcher._marshaled_dispatch(request.raw_post_data)) response['Content-Length'] = str(len(response.content)) return response TRACKBACK_SUCCESS_RESPONSE = '<?xml version="1.0" encoding="utf-8"?><response><error>0</error></response>' TRACKBACK_FAILURE_RESPONSE = '<?xml version="1.0" encoding="utf-8"?><response><error>1</error><message>An error occurred</message></response>'
def get_project(p_slug): """ arguments: String:project_slug <br/> get some information about a project """ try: p = Project.objects.get(slug=p_slug) pd = model_to_dict(p) fields = ['is_inactive', 'hide', 'description', 'tags', #'markup', 'homepage_link', 'summary', 'name'] return dict([(k, pd[k]) for k in fields]) except Project.DoesNotExist: return None dispatcher.register_function(get_project, 'get_project') def _get_latest_release(project_slug): r = Release.objects.filter(project__slug=project_slug, project__is_inactive=False) if r.count(): return r[0] def get_latest_version(p_slug): """ arguments: String:project_slug <br/> get the name of the latest version of a project """ r = _get_latest_release(p_slug) if r:
""" Pozwala zdalnei dodawac wpisy do konta """ try: p = UserProfile.objects.get(current_salt=salt) except: return dodaj_prywatny_wpis(tresc, syntax) w = Wklejka(nickname=p.username(), body=tresc, syntax=syntax, user=p.user, is_private=True) w.save() salt = sha.new(str(random.random())).hexdigest()[:10] hash = sha.new(salt).hexdigest()[:10] w.hash = hash w.save() return w.get_absolute_url() # you have to manually register all functions that are xml-rpc-able with the # dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from # the XML-RPC side... dispatcher.register_function(dodaj_wpis, 'dodaj_wpis') dispatcher.register_function(dodaj_prywatny_wpis, 'dodaj_prywatny_wpis') dispatcher.register_function(auth_dodaj_wpis, 'auth_dodaj_wpis') dispatcher.register_function(auth_dodaj_prywatny_wpis, 'auth_dodaj_prywatny_wpis')
# but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write( '<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>' ) response['Content-length'] = str(len(response.content)) return response def multiply(a, b): """ Multiplication is fun! Takes two arguments, which are multiplied together. Returns the result of the multiplication! """ return a * b # you have to manually register all functions that are xml-rpc-able with the dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from the XML-RPC side... dispatcher.register_function(multiply, 'multiply')
result = [] for post in posts: result.append({ 'postid' : str(post.key().id()), 'dateCreated' : post.date, 'title' : post.title, 'description' : unicode(post.content), 'categories' : post.tags, 'publish' : True, }) return result def blogger_deletePost(appkey, postid, username, password, publish): user = check_admin(username, password) if not user: raise Exception, 'access denied' post = Post.get_by_id(int(postid)) post.delete() return True dispatcher.register_function(blogger_getUsersBlogs,'blogger.getUsersBlogs') dispatcher.register_function(metaWeblog_newPost,'metaWeblog.newPost') dispatcher.register_function(metaWeblog_editPost,'metaWeblog.editPost') dispatcher.register_function(metaWeblog_getCategories,'metaWeblog.getCategories') dispatcher.register_function(metaWeblog_getPost,'metaWeblog.getPost') dispatcher.register_function(blogger_deletePost,'blogger.deletePost')
if email_re.search(username): try: contact = crm.Contact.objects.get(user__email=username) except crm.Contact.DoesNotExist: contact = None else: try: contact = crm.Contact.objects.get(user__username=username) except crm.Contact.DoesNotExist: contact = None return contact def authenticate(username, password): return bool(auth.authenticate(username=username, password=password)) dispatcher.register_function(authenticate, 'authenticate') def project_relationships(project_trac_env, username): groups = [] contact = _get_contact(username) if contact: groups = crm.RelationshipType.objects.filter( project_relationships__contact=contact, project_relationships__project__trac_environment=project_trac_env, ).values_list('slug', flat=True) return list(groups) dispatcher.register_function(project_relationships, 'project_relationships') def callerid(number):
sys.stderr.flush() return "", 0 def classNames(prefix): return [it[0] + ":" + it[1] for it in autoimp.import_assist(prefix)] def stopServ(): print "rope server stoping..." global myGlobalisServerSatrt myGlobalisServerSatrt = False srv.register_function(stopServ, "stopServ") srv.register_function(initProject, "initProject") srv.register_function(errorsList, "errorsList") srv.register_function(revalidate, "revalidate") srv.register_function(autocompletitionList, "autocompletitionList") srv.register_function(findImplementation, "findImplementation") srv.register_function(classNames, "classNames") class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass import struct
if len(numbers_1)!= 0: owner = numbers_1[0].client_id if len(numbers_2)!= 0: source = "22738"+source owner = numbers_2[0].client_id Connection.objects.create(source=source,destination=destination, duration=duration,start=start, end=end, operator=operator, uniqueid=uniqueid,host=host,type=type, owner=owner) return True #return source dispatcher.register_function(bill, 'bill')
for method in methods: # right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') response['Content-length'] = str(len(response.content)) return response def add_patch(name, diff): """ Add a patch. """ p = Patch(name=name, diff=diff) p.save() return 'Patch added...' # you have to manually register all functions that are xml-rpc-able with the dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from the XML-RPC side... dispatcher.register_function(add_patch, 'add_patch')
('http://example.com/good-source-document/', 'http://example.com/blog/pingable-entry/'): 'Ping registered' } def mock_ping(sourceURI, targetURI): response = mock_responses.get((sourceURI, targetURI), Fault(0, 'Error')) if isinstance(response, Fault): raise response return response try: dispatcher = SimpleXMLRPCDispatcher() except TypeError: dispatcher = SimpleXMLRPCDispatcher(allow_none=False, encoding=None) dispatcher.register_function(mock_ping, "pingback.ping") def mock_pingback_server(request): if not request.method == 'POST': return HttpResponseNotAllowed(['POST']) response = HttpResponse(mimetype='text/xml') response.write(dispatcher._marshaled_dispatch(request.body)) response['Content-Length'] = str(len(response.content)) return response TRACKBACK_SUCCESS_RESPONSE = '<?xml version="1.0" encoding="utf-8"?><response><error>0</error></response>' TRACKBACK_FAILURE_RESPONSE = '<?xml version="1.0" encoding="utf-8"?><response><error>1</error><message>An error occurred</message></response>' def mock_trackback_server(request, id): try: id = int(id)
return False registrations = { 'whatis_ip': whatis_ip, 'whois_ip': whois_ip, 'whoami': whoami, 'ping': ping, 'usage': usage, 'usage_history': usage_history, 'coffee_ip': coffee_ip, 'r_disown_mac': r_disown_mac, } for k in registrations: dispatcher.register_function(registrations[k], k) # converts a datetime object to an integer with seconds since the unix epoch class JSONDateTimeEncoder(json.JSONEncoder): def default(self, o=datetime): return mktime(o.timetuple()) def httpget_handler(request, output_format, method): # this handles requests through our "simple" api handler. # this outputs in a few formats. output_format = output_format.lower() supported_formats = ['json', 'pickle', 'csv', 'python'] if output_format not in supported_formats:
else: response = HttpResponse() response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: # right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) # @ReservedAssignment response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response.write('<a href="http://www.djangoproject.com/"> <img src="http://media.djangoproject.com/img/badges/djangomade124x25_grey.gif" border="0" alt="Made with Django." title="Made with Django."></a>') response['Content-length'] = str(len(response.content)) return response def add_lot(item_dict): store_service = SpiderStoreService() return store_service.add_lot(item_dict) dispatcher.register_function(add_lot, 'add_lot')
response = HttpResponse() if(len(request.POST)): response.write( dispatcher._marshaled_dispatch(request.raw_post_data)) else: response.write("<b>This is an XML-RPC Service.</b><br>") response.write("You need to invoke it using an XML-RPC Client!<br>") response.write("The following methods are available:<ul>") methods = dispatcher.system_listMethods() for method in methods: # right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) response.write("<li><b>%s</b>: [%s] %s" % (method, sig, help)) response.write("</ul>") response['Content-length'] = str(len(response.content)) return response import caso.collect.urls for key in caso.collect.urls.xmlrpc_functions: dispatcher.register_function(caso.collect.urls.xmlrpc_functions[key],key)
Keys of the structure returned: translation -- Translated term. revisiondate -- Last term revision. standardized -- Whether it's a standardized term or not. """ result = {} # XXX: The following search needs to become a function to be used on both # get_translations and translations.views.index. # While we don't have a definitive way to search we use this. words = Word.objects.filter(term__contains=term).order_by('term') for word in words: trans = [] sentences = Sentence.objects.filter(words__term=word.term).order_by('length') for sentence in sentences: translations = Translation.objects.filter(language__short_name=language).filter(sentence__id=sentence.id) for translation in translations: trans.append({ 'translation': translation.msgstr, 'revisiondate': translation.revisiondate, 'standardized': translation.standardized }) result[word.term] = trans return result rpc_dispatcher.register_function(get_translation) rpc_dispatcher.register_function(get_languages) rpc_dispatcher.register_function(get_status)
query_filter = None for field, values in query.iteritems(): for value in values: if field not in field_map: continue field_filter = Q(**{field_map[field]: value}) if not query_filter: query_filter = field_filter continue if operator == 'and': query_filter &= field_filter else: query_filter |= field_filter result = [] packages = models.Package.objects.filter(query_filter).all()[:20] for package in packages: release = package.releases.all()[0] result.append({ 'name': package.name, 'summary': release.summary, 'version': release.version, '_pypi_ordering': 0, }) return result dispatcher.register_function(search, 'search')
# right now, my version of SimpleXMLRPCDispatcher always # returns "signatures not supported"... :( # but, in an ideal world it will tell users what args are expected sig = dispatcher.system_methodSignature(method) # this just reads your docblock, so fill it in! help = dispatcher.system_methodHelp(method) string+= "<li><b>%s</b>: %s" % (method, help) string+="</ul>" return render_to_response("xmlrpc.html",{"appBody":string}) def multiply(a, b): """ Multiplication is fun! Takes two arguments, which are multiplied together. Returns the result of the multiplication! """ return a*b # you have to manually register all functions that are xml-rpc-able with the dispatcher # the dispatcher then maps the args down. # The first argument is the actual method, the second is what to call it from the XML-RPC side... dispatcher.register_function(multiply, 'multiply') #dispatcher.register_function(get_data,'info'); dispatcher.register_function(return_array, 'test') dispatcher.register_function(show_data,'echo') dispatcher.register_function(save_image,'saveImage') dispatcher.register_function(save_find,'saveFind') dispatcher.register_function(save_instance,'saveInstance') #dispatcher.register_introspection_functions()
obsolete=False, ).values( 'sentence__msgid', 'msgstr', 'sentence__length', ).order_by( 'sentence__length', 'sentence__msgid', 'msgstr' ).distinct() for translation in translations: # I don't like this but for now it's ok packages = Translation.objects.filter( language__short_name=language, sentence__msgid=translation['sentence__msgid'] ).order_by( 'package__name' ) result.append({ 'original': translation['sentence__msgid'], 'translation': translation['msgstr'], 'packages': [x.package.name for x in packages], }) return result rpc_dispatcher.register_function(get_translation) rpc_dispatcher.register_function(get_languages) rpc_dispatcher.register_function(get_status)