Search code examples
pythonpython-3.xflaskflask-restful

Unable to call flask method from another flask method of same python file


Unable to call flask method from another flask method of same python file. For example, consider the code below

@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.

How to resolve this issue


Solution

  • Flask Function will expect an http request. You can create command function without Flask app.route decorator. This will be helpful to separate functionality and http request .For example below:

    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.