Ticket #30995: converter_test.py

File converter_test.py, 1.8 KB (added by Jack Cushman, 5 years ago)

Single-file Django project demonstrating type-matching based url resolution

Line 
1# single-file django via https://github.com/readevalprint/mini-django/blob/master/pico_django.py
2# run with django dev server:
3# $ pip install Django
4# $ PYTHONPATH=. django-admin.py runserver 0.0.0.0:8000 --settings=converter_test
5
6
7import random
8from django.http import HttpResponse
9from django.urls import path, register_converter, reverse
10from django.urls.converters import IntConverter
11
12
13## settings
14
15DEBUG = True
16ROOT_URLCONF = 'converter_test'
17ALLOWED_HOSTS = '*'
18DATABASES = {'default': {}}
19SECRET_KEY = "not so secret"
20
21
22## views
23
24def index(request):
25 # simulate a generic "export thing" template that might be asked to link to a Foo or a Bar:
26 some_foo_or_bar = Foo(1) if random.randint(0, 1) else Bar(1)
27 return HttpResponse("Export your %s: %s" % (some_foo_or_bar, reverse('export', args=[some_foo_or_bar])))
28
29
30## url converters
31
32# in reality these might be two different Django models
33class Foo(int): pass
34class Bar(int): pass
35
36class FooConverter(IntConverter):
37 def to_python(self, value):
38 return Foo(value)
39
40 def to_url(self, obj):
41 if type(obj) is not Foo:
42 # returning '' will cause the route not to match, but returning ValueError would be more consistent
43 return ''
44 return super().to_url(obj)
45
46class BarConverter(IntConverter):
47 def to_python(self, value):
48 return Bar(value)
49
50 def to_url(self, obj):
51 if type(obj) is not Bar:
52 # returning '' will cause the route not to match, but returning ValueError would be more consistent
53 return ''
54 return super().to_url(obj)
55
56register_converter(FooConverter, 'foo')
57register_converter(BarConverter, 'bar')
58
59
60## urls
61
62urlpatterns = [
63 path('', index),
64 path('export/foo/<foo:obj>', index, name='export'),
65 path('export/bar/<bar:obj>', index, name='export'),
66]
Back to Top