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?
- 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\$Kevin Brown-Silva– Kevin Brown-Silva2016-08-17 01:45:03 +00:00CommentedAug 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\$Joff– Joff2016-08-18 08:52:58 +00:00CommentedAug 18, 2016 at 8:52
1 Answer1
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.
- \$\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\$Joff– Joff2016-08-17 01:53:56 +00:00CommentedAug 17, 2016 at 1:53
You mustlog in to answer this question.
Explore related questions
See similar questions with these tags.