Flask-restful: multiple url handled by a single Resource class
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
api.add_resource(GBRest.Site,
'/sites/<sid>',
'/sites/<sid>/<site_properties>/<name>',
resource_class_kwargs={'config': CONFIG})
class Site(RestFulResource):
def _get_site(self, db: MongoAdapter, sid: str) -> Union[List, Dict]:
db.use_collection('sites')
sids = sid.split(',')
if len(sids) == 1:
return next(db.connected_ins.find({'_id': ObjectId(next(iter(sids)))}, {'_id': 0}))
elif len(sids) > 1:
return list(db.connected_ins.find({'_id': {
'$in': list(map(lambda _sid: ObjectId(_sid), sids))
}}, {'_id': 0}))
else:
raise ValueError("Invalid id")
def _get_service(self, db, sid, site_properties, name):
if any(name) and "," in sid:
raise ValueError("Invalid request")
_ = self._get_site(db, sid=sid)
if any(name):
if site_properties not in _.keys():
raise ValueError("Invalid request")
return _[site_properties][name]
return _
@exception_handle
def get(self, sid, site_properties="", name=""):
return GBResponse(
status=200,
message='request success',
success=True,
payload=self.execute(self._get_service, sid=sid, site_properties=site_properties, name=name)
).json()