2

I had my Flask routes defined like this:

@api_app.route('/api/1.0/infrastructure/', methods=['POST'])
def create_infrastructure():

     return (jsonify({'job': job_instance.reference}), 202,
                    {'Location': url_for('get_job', ref=job_instance.reference, _external=True)})

get_job function:

@api_app.route('/api/1.0/job/<string:ref>', methods=['GET'])
def get_job(ref):

        job = Model.Job.query.filter_by(reference=ref).first()
        if not job:
            abort(400)
        return jsonify({'job': job.reference})

I migrated to a flask.ext.restful environment and now looks like this:

from flask.ext.restful import Resource
    class Job(Resource):
        def get(self, ref):
            job = Model.Job.query.filter(Model.Job.reference == ref).first()
            if job:
               return jsonify(job.serialize())

            resp = Response(status=404, mimetype='application/json')
            return resp

In this class based API using flask.ext.restful How to define the url_for parameters in this class based environment?

In my main app file:

api.add_resource(Job, '/api/1.0/job/<string:ref>')
imbue_api.add_resource(Infrastructures, '/api/1.0/infrastructure')
gogasca
  • 9,283
  • 6
  • 80
  • 125

2 Answers2

3

The easiest way is to just use flask-restful's Api.url_for.

So instead of writing

url_for('get_job', ...)

You would have to

from flask_restful import Api

Api.url_for(Job, ...)

Note: It is important to make sure you don't create circular imports by importing classes into each other. My personal preferred way to organize this is to import all involved resouces in the __init__.py and then if you want to link to them you import .Job, that way you enforce a clean import order.

replay
  • 3,569
  • 3
  • 21
  • 30
0

Thanks I used the following:

from flask import current_app
api = restful.Api

In my Infrastructure class:

response.headers['Location'] = api.url_for(api(current_app),
                                                           Job,
                                                           ref=job_instance.reference,
                                                           _external=True)

And works fine now

gogasca
  • 9,283
  • 6
  • 80
  • 125