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

标签 python node.js api xml-rpc simplexmlrpcserver

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

编辑

好的,感谢@upman 的回答,我知道我可以为此使用 SimpleXMLRPCServer,问题仍然是:如何在用其他语言编写的其他程序中收听 XML-RPC 服务器比 python(例如 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 是一个 standard protocol , 所以有它的实现 在大多数流行语言中。有一个 package对于 Node 也是如此。 你可以像这样用 npm 安装

npm 安装 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 - 创建一个 SimpleHTTPServer 以使用 python 代码作为 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652679/

相关文章:

node.js - Nginx + NodeJS 重定向到端口 80

android - 将 .ics 文件恢复到 Android 手机日历中

python - Rabbitmq hello world 连接仅适用于本地主机(python)

python - 使用 Python 列表创建多边形坐标

javascript - PDF 到可编辑文档

c++ - 如何获得规范套接字的 "CLOSE_WAIT"状态

linux - 使用 Pip 安装 Twilio 时遇到问题

python - 在 Django 1.11 中使用 SelectDateWidget 的空选择

python - 为什么 1//0.05 在 python 中结果为 19.0?

javascript - 如何将消息保存到txt?