Reputation: 255
In my views.py I have following code:
# Exceptions for GET requests
try:
page = int(request.GET["page"])
except Exception:
page = 1
try:
price_from = request.GET["price_from"]
except Exception:
price_from = -5
try:
price_to = request.GET["price_to"]
except Exception:
price_to = "all"
# ...
# Another 10+ try/except statements for now, but more will come
I need to get variables from GET request, which can but doesnt have to be declared in link. Is there any cleaner/better way to do this, or it is normal to have tons of try/except in code? Thanks.
Upvotes: 1
Views: 107
Reputation: 95682
Just use the get
method and provide a default:
try:
page = int(request.GET.get("page", 1))
except ValueError:
page = 1
price_from = request.GET.get("price_from", -5)
price_to = request.GET.get("price_to", "all")
and even when you do need to handle an exception try to handle only the exception you are expecting otherwise other errors might pass unnoticed.
Upvotes: 6