1
\$\begingroup\$

I kind of started making an API for my site in a Django class based view because it seemed logical and now it has gotten quite large and unruly and I am starting to wonder if I am doing this correctly.

class URLAPI(View):    def get(self, request):         if request.GET.get('param') == "foo":             ...         elif request.GET.get('param') == "bar":             ...         elif request.GET.get('param') == "foo" and request.GET.get('param2') == "arg":             ...

I did the same thing with the post function creating conditionals for the data that is coming in. What do you think about this?

askedAug 16, 2016 at 2:25
Joff's user avatar
\$\endgroup\$
2
  • 1
    \$\begingroup\$Huge recommendation: use an existing framework like Django REST framework instead of rolling your own. You'll save a lot of time down the road, because you won't have to handle all of the special casing that's required. (Disclaimer: I'm a maintainer of DRF, but if there is a better API framework that suits your needs, my comment also applies to it)\$\endgroup\$CommentedAug 17, 2016 at 1:45
  • \$\begingroup\$I've been meaning to look into that, I had this one nearly complete by the time I realized that did what I needed. Will definitely check it out in the future\$\endgroup\$CommentedAug 18, 2016 at 8:52

1 Answer1

3
\$\begingroup\$

If you are going to have a lot of cases, and each one is quite complex (more than a few lines) I would ditch theif/elif approach.

Instead I would have inner functions, one for each case. Then a dictionary will map each case ('foo','bar' etc) to its function.

For example:

class URLAPI(View):    def get(self, request):        def act_on_foo():            ...        def act_on_bar():            ...        func_dict = {'foo': act_on_foo,                     'bar': act_on_bar}        param = request.GET.get('param')        func_dict[param]()

Perhaps an even better design would be to move theact_on_foo andact_on_bar functions to another module to decouple the view from the logic behind it.


And some nitpicking: Try to avoid mixing" and' in the same piece of code. Pick one and stick to it.

answeredAug 16, 2016 at 6:39
DeepSpace's user avatar
\$\endgroup\$
1
  • \$\begingroup\$ahh I know about the " and ' it is bothering me too. I switched some time back to " and I didn't want to go through the code and change everything\$\endgroup\$CommentedAug 17, 2016 at 1:53

You mustlog in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.