【问题标题】:Create a SimpleHTTPServer to use the python code as API创建一个 SimpleHTTPServer 以使用 python 代码作为 API
【发布时间】:2015-11-11 14:29:42
【问题描述】:

有没有办法让我的 python 脚本由 Simple HTTP 服务器提供服务,并在 API 理念中从外部(在其他程序中)调用脚本函数?

编辑

好的,感谢@upman 的回答,我知道我可以使用SimpleXMLRPCServer 来解决这个问题,但问题仍然存在:如何在使用 Python 以外的其他语言编写的其他程序中收听 XML-RPC 服务器(Node.以js为例)

【问题讨论】:

    标签: python node.js api xml-rpc simplexmlrpcserver


    【解决方案1】:

    您所要求的称为远程过程调用 (RPC)

    您可以在 Python 中查看 SimpleXMLRPCServer 模块

    服务器代码

    from SimpleXMLRPCServer import SimpleXMLRPCServer
    from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
    
    # Restrict to a particular path.
    class RequestHandler(SimpleXMLRPCRequestHandler):
        rpc_paths = ('/RPC2','/')
    
    # Create server
    server = SimpleXMLRPCServer(("localhost", 8000),
                                requestHandler=RequestHandler)
    server.register_introspection_functions()
    
    # Register pow() function; this will use the value of
    # pow.__name__ as the name, which is just 'pow'.
    server.register_function(pow)
    
    # Register a function under a different name
    def adder_function(x,y):
        return x + y
    server.register_function(adder_function, 'add')
    
    # Register an instance; all the methods of the instance are
    # published as XML-RPC methods (in this case, just 'div').
    class MyFuncs:
        def div(self, x, y):
            return x // y
    
    server.register_instance(MyFuncs())
    
    # Run the server's main loop
    server.serve_forever()
    

    Python 客户端

    import xmlrpclib
    
    s = xmlrpclib.ServerProxy('http://localhost:8000')
    print s.pow(2,3)  # Returns 2**3 = 8
    print s.add(2,3)  # Returns 5
    print s.div(5,2)  # Returns 5//2 = 2
    
    # Print list of available methods
    print s.system.listMethods()
    

    来源:https://docs.python.org/2/library/simplexmlrpcserver.html

    编辑

    XMLRPC 是一个standard protocol,所以有它的实现 在大多数流行语言中。节点也有一个package。 你可以像这样用 npm 安装

    npm install xmlrpc

    你可以用它调用上面的python服务器

    Javascript 客户端

    var xmlrpc = require('xmlrpc')
    var client = xmlrpc.createClient({ host: 'localhost', port: 8000, path: '/'})
    
    // Sends a method call to the XML-RPC server
    client.methodCall('pow', [2,2], function (error, value) {
      // Results of the method response
      console.log('Method response for \'anAction\': ' + value)
    })
    

    还有一个jQuery implementation xmlrpc。因此,您可以从浏览器中进行 RPC。

    【讨论】:

    • 感谢您的回答,它看起来与我正在寻找的完全一样!但是如何使用 Python 以外的其他语言在客户端与服务器通信(例如 NodeJs)?
    • 编辑了答案。看看吧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    相关资源
    最近更新 更多