3

How to check what route has been used?

Using @api with Flask-restful and Python at the moment I'm not doing it in a clean way by checking api.endpoint value.

How do I do it correctly?

@api.route('/form', endpoint='form')
@api.route('/data', endpoint='data')
class Foobar(Resource):
    def post(self):
        if api.endpoint == 'api.form':
            print('form')
        elif api.endpoint == 'api.data':
            print('data')

EDIT:

Should I split it into two classes?

1
  • what guide are you following on Flask? I've never seen this unusual style. Commented Jul 29, 2019 at 10:16

2 Answers 2

4

I am in no way a professional with flask so please do take my answer with a grain of salt. First of all I would definitely split it into 2 different classes just to have a better overview of what you are doing. Also as a rule of thumb I would always split the apis and write its own logic for a higher degree of granularity.

Second if you want to have a look at https://flask-restful.readthedocs.io/en/latest/api.html#flask_restful.Api.owns_endpoint. This might be of assistance for you.

Sign up to request clarification or add additional context in comments.

Comments

4

I am new with python and flask.

I think something like the following should work for you:

from flask import Flask, request
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)


class Data(Resource):
    def post(self):
        print("data")
        return{"type": "data"}


class Form(Resource):
    def post(self):
        print("form")
        return{"type": "form"}


api.add_resource(Form, '/form')
api.add_resource(Data, '/data')

if __name__ == "__main__":
    app.run(port=8080)

Also you have use seperate files for the classes for a cleaner code like:

form.py

from flask_restful import Resource


class Form(Resource):
    def post(self):
        print("form")
        return{"type": "form"}

data.py

from flask_restful import Resource


class Data(Resource):
    def post(self):
        print("data")
        return{"type": "data"}

services.py

from flask import Flask, request
from flask_restful import Api
from data import Data
from form import Form

app = Flask(__name__)
api = Api(app)


api.add_resource(Form, '/form')
api.add_resource(Data, '/data')

if __name__ == "__main__":
    app.run(port=8080)

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.