创建一个SimpleHTTPServer以使用python代码作为API

2024-09-29 23:31:21 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以让我的python脚本由一个简单的HTTP服务器提供服务,并从外部(在另一个程序中)调用脚本函数?在

编辑

好吧,多亏了@upman的回答,我知道我可以使用SimpleXMLRPCServer来实现这一点,问题仍然是:如何在用python以外的语言编写的其他程序中监听XML-RPC服务器(节点.js例如)


Tags: 方法函数程序服务器脚本语言http编辑
1条回答
网友
1楼 · 发布于 2024-09-29 23:31:21

你要的是远程过程调用(RPCs)

您可以查看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客户端

^{pr2}$

来源: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 implementationxmlrpc。所以你可以从浏览器制作rpc。在

相关问题 更多 >

    热门问题