Organize a sophisticated URL manager

I have two different types of objects that I would like to live on the same URL. One group of objects should be passed to the "foo" view function, and another group should be passed to "bar".

I am currently doing this with a large long list of hard-tuned URLs like ...

urlpatterns = patterns('project.views',
    (r'^a/$', 'foo'),
    (r'^b/$', 'foo'),
    (r'^c/$', 'foo'),
    #...and so on until...
    (r'^x/$', 'bar'),
    (r'^y/$', 'bar'),
    (r'^z/$', 'bar'),
)

Is it possible to define a list of each type of URL, for example ...

foo_urls = ['a', 'b', 'c'] #...
bar_urls = ['x', 'y', 'z'] #...

... and then check the incoming URL for these lists? (If it is in 'foo_urls', send 'project.views.foo', if it is in 'bar_urls', send to 'project.views.bar')?

I will limit myself to this structure supporting compatibility with URLs from the previous site, but any tips on ways to simplify my urls.py would be appreciated.

+3
4

url , . URL ?

foo_urls = ['a', 'b', 'c'] #...
bar_urls = ['x', 'y', 'z'] #...

# A first pattern to get urlpatterns started.
urlpatterns = pattern('project.views', 
    ('blah', 'blah')
    )

# Append all the foo urls.
for foo_url in foo_urls:
    urlpatterns += patterns('project.views',
        ('^' + foo_url + '/$', 'foo')
        )

# Append all the bar urls.
for bar_url in bar_urls:
    urlpatterns += patterns('project.views',
        ('^' + bar_url + '/$', 'bar')
        )
+5

url Django , :

urlpatterns = patterns('project.views',
    (r'^[abc]/$', 'foo'),
    (r'^[xyz]/$', 'bar'),
)

a, b, c - , , , , :

urlpatterns = patterns('project.views',
    (r'^(foo|slithy|toves)/$', 'foo'),
    (r'^(bar|twas|brillig)/$', 'bar'),
)
+4

urlpatterns , URL-, foo bar URL- .

urlpatterns = patterns('project.views',
    (r'^(?P<letter>[a-z])/$', 'foobar'),
)

foobar views.py

def foobar(request, letter):

    foo_urls = ['a', 'b', 'c'] #...
    bar_urls = ['x', 'y', 'z'] #...
    if slug in foo_urls:
        return foo(request)
    if slug in bar_urls:
        return bar(request)
    else:
         #oh dear, you've caught a
         #url that isn't foo or bar
         #return 404?

django , URL-, URL-.

+3

Apache :

<LocationMatch "^[a-w]/$">
   ...
</LocationMatch>

<LocationMatch "^[x-z]/$">
   ...
</LocationMatch>

... config, , SetEnv, , , foo vs bar , , ProxyPass URLs.

URL Apache, regex.

+1

Source: https://habr.com/ru/post/1718426/


All Articles