创build一个SimpleHTTPServer来使用Python代码作为API

有没有办法使我的python脚本服务于一个简单的HTTP服务器,并调用脚本函数从外部(在另一个程序)在API的哲学?

编辑

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

您所要求的称为远程过程调用(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是一个标准的协议 ,所以在大多数stream行的语言中都有它的实现。 还有一个节点包 。 你可以这样安装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实现 xmlrpc。 所以你可以从浏览器中创buildRPC。