【问题标题】:Unable to call flask method from another flask method of same python file无法从同一 python 文件的另一个烧瓶方法调用烧瓶方法
【发布时间】:2020-04-05 06:26:54
【问题描述】:

无法从同一 python 文件的另一个烧瓶方法调用烧瓶方法。例如,考虑下面的代码

@app.route('/api/v1/employee/add', method = ['POST'])
def add_employee():
    req = request.json
    #add the employee to db

@app.route('/api/v1/employee', method = ['GET'])
def get_employee():
    data = json.loads(employee) #getting employee details from db
    add_employee() # unable to call this method as I am getting the data as null.

如何解决此问题

【问题讨论】:

    标签: python python-3.x flask flask-restful


    【解决方案1】:

    Flask 函数需要一个 http 请求。您可以在没有 Flask app.route 装饰器的情况下创建命令函数。这将有助于分离功能和 http 请求。例如:

    def add_employee():
        # Add Some Query here
        pass
    
    
    
    @app.route('/api/v1/employee/add', method = ['POST'])
    def http_employee():
        req = request.json
        add_employee()
    
    
    @app.route('/api/v1/employee', method = ['GET'])
    def get_employee():
        data = json.loads(employee) #getting employee details from db
        add_employee() # unable to call this method as I am getting the data as null.
    
    

    【讨论】:

    • 仍然面临同样的问题,我所尝试的只是将 add_employee 代码块作为单独的方法移动并在 POST API 和 GET API 中调用。 POST API 工作正常,但仍然从 GET API 调用 add_employee 会引发 NoneType 错误。
    • 这是因为你需要返回一些东西来防止flask throw NoneType 错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多