Reputation: 2718
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?
Upvotes: 3
Views: 4229
Reputation: 626
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.
Upvotes: 4
Reputation: 2137
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.
Upvotes: 4