gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:18:45 25 4
gpt4 key购买 nike

有没有办法让我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com