【问题标题】:Call Method of another class in Flask APIFlask API中另一个类的调用方法
【发布时间】:2020-02-03 11:45:48
【问题描述】:

我正在尝试将数据服务公开为 PHP 应用程序的 API。我在一个名为 APILogic.py 的文件中编写了 API 逻辑。这里面的代码是这样的

class APILogic(object):
    def __init__(self):
        # the initialization is done here
        ...

    def APIfunction(self):
        # the API logic is built here, it uses the class variables and methods
        ...

我为 API 目的创建了另一个文件。它称为 API.py。该文件中的代码如下所示

import APILogic from APILogic
class MyFlask:
    def __init__(self):
        self.test = APILogic()

from flask import Flask
app = Flask(__name__)

my_flask = MyFlask()

@app.route("/Test")
def Test():
    return my_flask.test.APIfunction

if __name__ == "__main__":
    app.run(debug=True,port=9999)

当我运行代码时,我得到了错误

> TypeError: APIfunction() takes 1 positional argument but 3 were given
The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a method.

API 函数没有参数。

请帮忙。

【问题讨论】:

  • @AkshayNevrekar 我已经在使用 ()。现在编辑问题。

标签: python-3.x rest oop flask


【解决方案1】:

视图函数未返回有效响应。返回类型必须是字符串、字典、元组、响应实例或 WSGI 可调用,但它是一个方法。

看起来您正在返回方法,但听起来您想返回该方法的结果:

@app.route("/Test")
def Test():
    return my_flask.test.APIfunction()

【讨论】:

    【解决方案2】:

    查看函数应返回有效响应。 示例 API 代码

    from flask import Flask
    
    app = Flask(__name__)
    
    @app.route("/")
    def hello():
        return "Hello World!"
    
    if __name__ == "__main__":
        app.run()
    

    【讨论】:

    • 我知道这一点。我试图从这里的另一个调用中调用一个方法。我现在开始工作了。谢谢
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多