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 |
|
---|
7 | import random
|
---|
8 | from django.http import HttpResponse
|
---|
9 | from django.urls import path, register_converter, reverse
|
---|
10 | from django.urls.converters import IntConverter
|
---|
11 |
|
---|
12 |
|
---|
13 | ## settings
|
---|
14 |
|
---|
15 | DEBUG = True
|
---|
16 | ROOT_URLCONF = 'converter_test'
|
---|
17 | ALLOWED_HOSTS = '*'
|
---|
18 | DATABASES = {'default': {}}
|
---|
19 | SECRET_KEY = "not so secret"
|
---|
20 |
|
---|
21 |
|
---|
22 | ## views
|
---|
23 |
|
---|
24 | def 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
|
---|
33 | class Foo(int): pass
|
---|
34 | class Bar(int): pass
|
---|
35 |
|
---|
36 | class 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 |
|
---|
46 | class 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 |
|
---|
56 | register_converter(FooConverter, 'foo')
|
---|
57 | register_converter(BarConverter, 'bar')
|
---|
58 |
|
---|
59 |
|
---|
60 | ## urls
|
---|
61 |
|
---|
62 | urlpatterns = [
|
---|
63 | path('', index),
|
---|
64 | path('export/foo/<foo:obj>', index, name='export'),
|
---|
65 | path('export/bar/<bar:obj>', index, name='export'),
|
---|
66 | ]
|
---|