Python – Call Pre-defined Function after Decorator


I am building a straight-forward Flask API. After each decorator for the API endpoint, I have to define a function that simply calls another function I have in a separate file. This works fine, but seems redundant. I would rather just call that pre-defined function directly, instead of having to wrap it within another function right after the decorator. Is this possible?

What I have currently:

import routes.Locations as Locations

# POST: /api/v1/locations
@app.route('/locations', methods=['GET'])
def LocationsRead ():
   return function looks like this:

def read():
   return {
      'id': 1,
      'name': 'READ'

What I am hoping to do:

import routes.Locations as Locations

# POST: /api/v1/locations
@app.route('/locations', methods=['GET'])


Thanks to @Dunes and @RodrigoRodrigues answers, I played around with it more and found that the following works both for endpoints with and without arguments to pass, like an ID. See the code below.

# GET: /api/v1/locations
app.route(basepath + '/locations', methods=['GET'])(
# GET: /api/v1/locations/{id}
app.route(basepath + '/locations/<int:id>', methods=['GET'])(
# POST: /api/v1/locations
app.route(basepath + '/locations', methods=['POST'])(Locations.create)
# PUT: /api/v1/locations/{id}
app.route(basepath + '/locations/<int:id>', methods=['PUT'])(Locations.update)
# DELETE: /api/v1/locations/{id}
app.route(basepath + '/locations/<int:id>', methods=['DELETE'])(Locations.delete)

Now, I doubt this is standard practice, but if someone is looking to reduce the amount of code in their route declarations, this is one way to do it.

Answered By – Austin Wilcox

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published