python - 将 Python 类函数公开为 REST 服务

标签 python rest

所以我有一个 Python 库,其中包含一堆 super 有用的函数。我希望能够通过 RESTful 接口(interface)调用此库的函数,以使这些函数可用于支持套接字并希望使用它们的任何语言、应用程序或进程。

我不想将每个函数单独编码为 RESTful 直通,因为有数百个函数可用,而且它们都可能发生变化。是否有符合标准的方法来公开这些功能以通过 REST 访问?

非常感谢任何人可以提供的任何想法、项目链接或建议:)

法国

最佳答案

我在您的问题下的评论中提出的几乎是:


main.py

from flask import Flask
from flask import request

import functions

app = Flask(__name__)


@app.route('/call/<function_name>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def call_function(function_name: str):
    function_to_call = getattr(functions, function_name)
    body = request.json
    return function_to_call(body)


app.run(host="0.0.0.0")

函数.py

def hello_world():
    return "Hello world!"


def hello_name(params: dict):
    name = params["name"]
    return "Hello " + name

请求示例:

  • 获取

http://localhost:5000/call/hello_world

  • 发布

http://localhost:5000/call/hello_name

{
  "name": "Tom"
}

关于python - 将 Python 类函数公开为 REST 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51991365/

相关文章:

angular - 响应重定向(302)在 Angular 不起作用

python - MySQL CREATE TABLE 在 DDL 语句中添加额外的行

休息 API : Obtaining Payment ID after redirect back to merchant site

python从文本文件中逐行读取

python - 发现单元格名称与 Google 表格中的名称不同

java - Android:RESTful JDBC 代理。性能和安全性

node.js - 通过 Angular App 和 NodeJS 发送 GET/POST 请求到 express 服务器时如何修复 404 Not Found

scala - 对 multipart/form-data 进行 POST 调用时,加特林测试返回 504

python - Tornado 大文件下载

python - 获取 3 列中条件为 true 时的索引号