I created an API with Django and i am trying to route requests to different views for optimization purposes.
Here is what i'm trying to do: if the GET request is 127.0.0.1:8000/api/sales/?key=<KEY>&some_query=<some_value>&...
that query should be handled by a view called sales
. If the GET request contains a specific parameter called sale_value
the request should be routed to another view called large_sales
, for example 127.0.0.1:8000/api/sales/?key=<KEY>&sale_value=<INT>...
should be handled from the large_sales
view.
Here is what i tried:
urlpatterns = [
path('sales/', views.sales, name="sales"),
path('sales/sale_value<int:num>', views.large_sales, name="large_sales"),
]
This will route all the requests to sales
. How can i do this? Maybe with regex?
Edit: i can't handle this logic directly in the view because i want to cache these two queries with different TTL. Example:
@cache_page(1.5)
def sales(request):
...
@cache_page(10)
def large_sales(request):
...
CodePudding user response:
def sales(request):
try:
sale_value = request.GET['sale_value']
except:
return redirect(large_sales, num=11) # replace 11 with your number.
or try to use if condition (if sale_value != None:
)
CodePudding user response:
You can write a view which accesses request.GET and redirects accordingly.
You may also need to put defensive code in the view that you redirect to, to make sure that a user (or attacer) is not getting creative with completely insecure GET parameters!
With a class-based view you can subclass get ...
class SalesView( some_CBV_class):
...
def get( self, request, *args, **kwargs):
if request.GET.get( 'sale_value', None):
target = reverse('app:large_sales', kwargs={...}
) '?' request.GET.urlencode()
return HttpResponseRedirect( target)
return super().get( request, *args, **kwargs)
and for safety, maybe
class LargeSalesView( ...)
def get( self, request, *args, **kwargs):
if request.GET.get( 'sale_value', None) is None
target = reverse('app:sales', kwargs={...}
) '?' request.GET.urlencode()
return HttpResponseRedirect( target)
return super().get( request, *args, **kwargs)