Home > Net >  Is there a way in Django to expose only a certain range of URLs based on some predefined variable?
Is there a way in Django to expose only a certain range of URLs based on some predefined variable?

Time:11-30

I am basically trying to expose a a range of defined URLs in an application.

E.g., I have 10k x2 resources which I'm hosting at /metadata/type1_1 and /metadata/type2_1 where each resource grouping iterates up to type1_10000 and type2_10000 respectively (20,000 stored assets I intend to serve over a manually-driven interval).

As such, I'm trying to define a URL scheme such that

max_available_metadata = current_limit [e.g. this may be 300, 7777 etc.] and I only want to configure the URLs within the pattern up to this limit. e.g., if I sent it to 25, type1_1, type1_2...25 and likewise type2_1, type2_2... type2_25 would all map properly but attempting to go to metadata/type1_26 through type1_10000 would all return 404s, likewise for type 2.

I'll probably want to configure setting this via the django admin but this isn't part of the question.

CodePudding user response:

You can control this in your view.

# urls.py
urlpatterns = [
    path(
        "metadata/type<int:asset_type>_<int:asset_num>/",
        views.serve_asset,
    ),

# views.py
def serve_asset(request, asset_type, asset_num):
    if asset_type == 1:
        if asset_num <= MAX_ALLOWED_ASSET_NUM:
            # do your stuff for asset 1
    elif asset_type == 2:
        ...
    raise Http404("Asset not exist")
  • Related