0

I've been using Flask-Classy for my server, and it works great. However, I've come across a use case that I haven't seen written about, but it's a pretty common use case, so I'd be shocked if it's not possible.

I have two APIs which I want to nest, and by that I mean I have:

class UsersView(FlaskView):
    decorators = [jwt_required()]
    route_prefix = '/api/v1/'

    def index(self):
    ...

which is located at http://example.com/api/v1/users and I can access user 1 via http://example.com/api/v1/users/1

Now, how would I write the FlaskView which would let me do something like this? http://example.com/api/v1/users/1/devices/3

When I try embedding the resource id in the route_prefix, I get a keyword argument error:

class DevicesView(FlaskView):
    decorators = [jwt_required()]
    route_prefix = '/api/v1/users/<user_id>/'

    def index(self):
    ...

TypeError: index() got an unexpected keyword argument 'user_id'

One last point is that I can, naturally, use kwargs:

route_prefix = '/api/v1/users/<user_id>/'

def test(self, **kwargs):
    print kwargs['user_id']

http://example.com/api/v1/users/103/devices will spit out '103', however, using kwargs feels kinda hokey. Is there a better way?

SJoshi
  • 1,866
  • 24
  • 47

2 Answers2

1

I put the top-level placeholder in the route_base in the register call.

For example:

class UsersView(FlaskView):
    @route('/', methods=['GET'])
    def index(self):
        pass

class DevicesView(FlaskView):
    @route('/', methods=['GET'])
    def index(self, user_id):
        pass

UsersView.register(app, route_base='/users', trailing_slash=False)
DevicesView.register(app, route_base='/users/<user_id>/devices', trailing_slash=False)

Now the user_id comes in as the first parameter on every method in DevicesView.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
jivetalker
  • 11
  • 1
0

In case you haven't found a solution as yet...The answer is pretty simple here you need to have the index defined as:

def index(self, user_id):

you have to do this since you would want to know the base resource through which to access the required resource. In your example devices index would give me a list of all devices belonging to the user. In order to get this information you will first need to know which user's devices are being asked for

Prasanjit Prakash
  • 409
  • 1
  • 6
  • 21
  • Thanks for the reply. Have you tried this and got it working? I've tried this before, and it throws a "ValueError: variable name 'user_id' used twice." – SJoshi Feb 27 '15 at 02:48