Skip to content

Commit 1d088d7

Browse files
committed
add new django code examples
1 parent 426d9b5 commit 1d088d7

File tree

34 files changed

+5947
-1
lines changed

34 files changed

+5947
-1
lines changed

content/pages/examples/django/django-extensions-plug-ins.markdown

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,6 +545,18 @@ and maintained by the collaborative developer community group
545545
[Jazzband](https://jazzband.co/).
546546

547547

548+
### django-user-visit
549+
[django-user-visit](https://github.com/yunojuno/django-user-visit)
550+
([PyPI package information](https://pypi.org/project/django-user-visit/))
551+
is a [Django](/django.html) app and
552+
[middleware](https://docs.djangoproject.com/en/stable/topics/http/middleware/)
553+
for tracking daily user visits to your web application. The goal
554+
is to record per user per day instead of for every request a user
555+
sends to the application. The project is provided as open source
556+
under the
557+
[MIT license](https://github.com/yunojuno/django-user-visit/blob/master/LICENSE).
558+
559+
548560
### django-webshell
549561
[django-webshell](https://github.com/onrik/django-webshell) is an extension
550562
for executing arbitrary code in the
@@ -584,6 +596,16 @@ The code for django-wiki is provided as open source under the
584596
[GNU General Public License 3.0](https://github.com/django-wiki/django-wiki/blob/master/COPYING).
585597

586598

599+
### elasticsearch-django
600+
[elasticsearch-django](https://github.com/yunojuno/elasticsearch-django)
601+
([PyPI package information](https://pypi.org/project/elasticsearch-django/))
602+
is a [Django](/django.html) app for managing
603+
[ElasticSearch](https://github.com/elastic/elasticsearch) indexes
604+
populated by [Django ORM](/django-orm.html) models. The project is
605+
available as open source under the
606+
[MIT license](https://github.com/yunojuno/elasticsearch-django/blob/master/LICENSE).
607+
608+
587609
### pytest-django
588610
[pytest-django](https://github.com/pytest-dev/pytest-django)
589611
([project documentation](https://pytest-django.readthedocs.io/en/latest/)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
title: django.utils.version get_complete_version Example Code
2+
category: page
3+
slug: django-utils-version-get-complete-version-examples
4+
sortorder: 500011513
5+
toc: False
6+
sidebartitle: django.utils.version get_complete_version
7+
meta: Python example code for the get_complete_version callable from the django.utils.version module of the Django project.
8+
9+
10+
get_complete_version is a callable within the django.utils.version module of the Django project.
11+
12+
13+
## Example 1 from django-webtest
14+
[django-webtest](https://github.com/django-webtest/django-webtest)
15+
([PyPI package information](https://pypi.org/project/django-webtest/))
16+
is a [Django](/django.html) extension that makes it easier to use
17+
[WebTest](http://docs.pylonsproject.org/projects/webtest/) with
18+
your projects.
19+
20+
The project is open sourced under the
21+
[MIT license](https://github.com/django-webtest/django-webtest/blob/master/LICENSE.txt).
22+
23+
[**django-webtest / django_webtest / backends.py**](https://github.com/django-webtest/django-webtest/blob/master/django_webtest/./backends.py)
24+
25+
```python
26+
# backends.py
27+
from __future__ import absolute_import
28+
~~from django.utils.version import get_complete_version
29+
from django.contrib.auth.backends import RemoteUserBackend
30+
from django_webtest.compat import from_wsgi_safe_string
31+
32+
class WebtestUserBackend(RemoteUserBackend):
33+
34+
~~ if get_complete_version() >= (1, 11):
35+
def authenticate(self, request, django_webtest_user):
36+
return super(WebtestUserBackend, self).authenticate(
37+
request, django_webtest_user)
38+
else:
39+
def authenticate(self, django_webtest_user):
40+
return super(WebtestUserBackend, self).authenticate(
41+
django_webtest_user)
42+
43+
def clean_username(self, username):
44+
return from_wsgi_safe_string(username)
45+
46+
47+
48+
## ... source file continues with no further get_complete_version examples...
49+
50+
```
51+
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
title: django.views csrf Example Code
2+
category: page
3+
slug: django-views-csrf-examples
4+
sortorder: 500011514
5+
toc: False
6+
sidebartitle: django.views csrf
7+
meta: Python example code for the csrf callable from the django.views module of the Django project.
8+
9+
10+
csrf is a callable within the django.views module of the Django project.
11+
12+
13+
## Example 1 from django-allauth
14+
[django-allauth](https://github.com/pennersr/django-allauth)
15+
([project website](https://www.intenct.nl/projects/django-allauth/)) is a
16+
[Django](/django.html) library for easily adding local and social authentication
17+
flows to Django projects. It is open source under the
18+
[MIT License](https://github.com/pennersr/django-allauth/blob/master/LICENSE).
19+
20+
21+
[**django-allauth / allauth / tests.py**](https://github.com/pennersr/django-allauth/blob/master/allauth/./tests.py)
22+
23+
```python
24+
# tests.py
25+
from __future__ import unicode_literals
26+
27+
import json
28+
import requests
29+
from datetime import date, datetime
30+
31+
import django
32+
from django.core.files.base import ContentFile
33+
from django.db import models
34+
from django.test import RequestFactory, TestCase
35+
from django.utils.http import base36_to_int, int_to_base36
36+
~~from django.views import csrf
37+
38+
from . import utils
39+
40+
41+
try:
42+
from unittest.mock import Mock, patch
43+
except ImportError:
44+
from mock import Mock, patch # noqa
45+
46+
47+
class MockedResponse(object):
48+
def __init__(self, status_code, content, headers=None):
49+
if headers is None:
50+
headers = {}
51+
52+
self.status_code = status_code
53+
self.content = content.encode('utf8')
54+
self.headers = headers
55+
56+
def json(self):
57+
return json.loads(self.text)
58+
59+
def raise_for_status(self):
60+
pass
61+
62+
63+
## ... source file abbreviated to get to csrf examples ...
64+
65+
66+
67+
self.assertEqual(serialized['bb'], 'c29tZSBiaW5hcnkgZGF0YQ==')
68+
self.assertEqual(serialized['bb_empty'], '')
69+
self.assertEqual(deserialized.bb, b'some binary data')
70+
self.assertEqual(deserialized.bb_empty, b'')
71+
72+
def test_build_absolute_uri(self):
73+
self.assertEqual(
74+
utils.build_absolute_uri(None, '/foo'),
75+
'http://example.com/foo')
76+
self.assertEqual(
77+
utils.build_absolute_uri(None, '/foo', protocol='ftp'),
78+
'ftp://example.com/foo')
79+
self.assertEqual(
80+
utils.build_absolute_uri(None, 'http://foo.com/bar'),
81+
'http://foo.com/bar')
82+
83+
def test_int_to_base36(self):
84+
n = 55798679658823689999
85+
b36 = 'brxk553wvxbf3'
86+
assert int_to_base36(n) == b36
87+
assert base36_to_int(b36) == n
88+
89+
def test_templatetag_with_csrf_failure(self):
90+
request = self.factory.get('/tests/test_403_csrf.html')
91+
~~ response = csrf.csrf_failure(
92+
request,
93+
template_name='tests/test_403_csrf.html'
94+
)
95+
self.assertEqual(response.status_code, 403)
96+
97+
98+
99+
## ... source file continues with no further csrf examples...
100+
101+
```
102+
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
title: django.views.debug get_default_exception_reporter_filter Example Code
2+
category: page
3+
slug: django-views-debug-get-default-exception-reporter-filter-examples
4+
sortorder: 500011515
5+
toc: False
6+
sidebartitle: django.views.debug get_default_exception_reporter_filter
7+
meta: Python example code for the get_default_exception_reporter_filter callable from the django.views.debug module of the Django project.
8+
9+
10+
get_default_exception_reporter_filter is a callable within the django.views.debug module of the Django project.
11+
12+
13+
## Example 1 from django-debug-toolbar
14+
[django-debug-toolbar](https://github.com/jazzband/django-debug-toolbar)
15+
([project documentation](https://github.com/jazzband/django-debug-toolbar)
16+
and [PyPI page](https://pypi.org/project/django-debug-toolbar/))
17+
grants a developer detailed request-response cycle information while
18+
developing a [Django](/django.html) web application.
19+
The code for django-debug-toolbar is
20+
[open source](https://github.com/jazzband/django-debug-toolbar/blob/master/LICENSE)
21+
and maintained by the developer community group known as
22+
[Jazzband](https://jazzband.co/).
23+
24+
[**django-debug-toolbar / debug_toolbar / panels / settings.py**](https://github.com/jazzband/django-debug-toolbar/blob/master/debug_toolbar/panels/settings.py)
25+
26+
```python
27+
# settings.py
28+
from collections import OrderedDict
29+
30+
import django
31+
from django.conf import settings
32+
from django.utils.translation import gettext_lazy as _
33+
34+
from debug_toolbar.panels import Panel
35+
36+
if django.VERSION >= (3, 1):
37+
~~ from django.views.debug import get_default_exception_reporter_filter
38+
39+
~~ get_safe_settings = get_default_exception_reporter_filter().get_safe_settings
40+
else:
41+
from django.views.debug import get_safe_settings
42+
43+
44+
class SettingsPanel(Panel):
45+
46+
template = "debug_toolbar/panels/settings.html"
47+
48+
nav_title = _("Settings")
49+
50+
def title(self):
51+
return _("Settings from <code>%s</code>") % settings.SETTINGS_MODULE
52+
53+
def generate_stats(self, request, response):
54+
self.record_stats(
55+
{
56+
"settings": OrderedDict(
57+
sorted(get_safe_settings().items(), key=lambda s: s[0])
58+
)
59+
}
60+
)
61+
62+
63+
64+
## ... source file continues with no further get_default_exception_reporter_filter examples...
65+
66+
```
67+
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
title: django.views.decorators.csrf csrf_exempt Example Code
2+
category: page
3+
slug: django-views-decorators-csrf-csrf-exempt-examples
4+
sortorder: 500011516
5+
toc: False
6+
sidebartitle: django.views.decorators.csrf csrf_exempt
7+
meta: Python example code for the csrf_exempt callable from the django.views.decorators.csrf module of the Django project.
8+
9+
10+
csrf_exempt is a callable within the django.views.decorators.csrf module of the Django project.
11+
12+
13+
## Example 1 from django-rest-framework
14+
[Django REST Framework](https://github.com/encode/django-rest-framework)
15+
([project homepage and documentation](https://www.django-rest-framework.org/),
16+
[PyPI package information](https://pypi.org/project/djangorestframework/)
17+
and [more resources on Full Stack Python](/django-rest-framework-drf.html)),
18+
often abbreviated as "DRF", is a popular [Django](/django.html) extension
19+
for building [web APIs](/application-programming-interfaces.html).
20+
The project has fantastic documentation and a wonderful
21+
[quickstart](https://www.django-rest-framework.org/tutorial/quickstart/)
22+
that serve as examples of how to make it easier for newcomers
23+
to get started.
24+
25+
The project is open sourced under the
26+
[Encode OSS Ltd. license](https://github.com/encode/django-rest-framework/blob/master/LICENSE.md).
27+
28+
[**django-rest-framework / rest_framework / viewsets.py**](https://github.com/encode/django-rest-framework/blob/master/rest_framework/./viewsets.py)
29+
30+
```python
31+
# viewsets.py
32+
from collections import OrderedDict
33+
from functools import update_wrapper
34+
from inspect import getmembers
35+
36+
from django.urls import NoReverseMatch
37+
from django.utils.decorators import classonlymethod
38+
~~from django.views.decorators.csrf import csrf_exempt
39+
40+
from rest_framework import generics, mixins, views
41+
from rest_framework.decorators import MethodMapper
42+
from rest_framework.reverse import reverse
43+
44+
45+
def _is_extra_action(attr):
46+
return hasattr(attr, 'mapping') and isinstance(attr.mapping, MethodMapper)
47+
48+
49+
class ViewSetMixin:
50+
51+
@classonlymethod
52+
def as_view(cls, actions=None, **initkwargs):
53+
cls.name = None
54+
cls.description = None
55+
56+
cls.suffix = None
57+
58+
cls.detail = None
59+
60+
cls.basename = None
61+
62+
if not actions:
63+
64+
65+
## ... source file abbreviated to get to csrf_exempt examples ...
66+
67+
68+
def view(request, *args, **kwargs):
69+
self = cls(**initkwargs)
70+
71+
if 'get' in actions and 'head' not in actions:
72+
actions['head'] = actions['get']
73+
74+
self.action_map = actions
75+
76+
for method, action in actions.items():
77+
handler = getattr(self, action)
78+
setattr(self, method, handler)
79+
80+
self.request = request
81+
self.args = args
82+
self.kwargs = kwargs
83+
84+
return self.dispatch(request, *args, **kwargs)
85+
86+
update_wrapper(view, cls, updated=())
87+
88+
update_wrapper(view, cls.dispatch, assigned=())
89+
90+
view.cls = cls
91+
view.initkwargs = initkwargs
92+
view.actions = actions
93+
~~ return csrf_exempt(view)
94+
95+
def initialize_request(self, request, *args, **kwargs):
96+
request = super().initialize_request(request, *args, **kwargs)
97+
method = request.method.lower()
98+
if method == 'options':
99+
self.action = 'metadata'
100+
else:
101+
self.action = self.action_map.get(method)
102+
return request
103+
104+
def reverse_action(self, url_name, *args, **kwargs):
105+
url_name = '%s-%s' % (self.basename, url_name)
106+
namespace = None
107+
if self.request and self.request.resolver_match:
108+
namespace = self.request.resolver_match.namespace
109+
if namespace:
110+
url_name = namespace + ':' + url_name
111+
kwargs.setdefault('request', self.request)
112+
113+
return reverse(url_name, *args, **kwargs)
114+
115+
@classmethod
116+
def get_extra_actions(cls):
117+
return [method for _, method in getmembers(cls, _is_extra_action)]
118+
119+
120+
## ... source file continues with no further csrf_exempt examples...
121+
122+
```
123+

0 commit comments

Comments
 (0)