Skip to content

Commit

Permalink
chore: Add example projects
Browse files Browse the repository at this point in the history
  • Loading branch information
sondrelg committed Nov 26, 2022
1 parent 4d6fc81 commit 38b9c22
Show file tree
Hide file tree
Showing 41 changed files with 739 additions and 291 deletions.
2 changes: 2 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ repos:
'flake8-annotations', # Enforces type annotation
]
args: ['--enable-extensions=G']
files: r'^django_guid'
- repo: https://github.com/asottile/pyupgrade
rev: v3.2.2
hooks:
Expand All @@ -46,3 +47,4 @@ repos:
rev: v0.991
hooks:
- id: mypy
files: r'^django_guid'
16 changes: 0 additions & 16 deletions demoproj/asgi.py

This file was deleted.

16 changes: 0 additions & 16 deletions demoproj/services/async_services.py

This file was deleted.

12 changes: 0 additions & 12 deletions demoproj/services/sync_services.py

This file was deleted.

28 changes: 0 additions & 28 deletions demoproj/urls.py

This file was deleted.

38 changes: 0 additions & 38 deletions demoproj/views/async_views.py

This file was deleted.

48 changes: 0 additions & 48 deletions demoproj/views/sync_views.py

This file was deleted.

11 changes: 0 additions & 11 deletions demoproj/wsgi.py

This file was deleted.

10 changes: 10 additions & 0 deletions examples/async-views/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Async views

Example code for setting up correlation IDs for async views.

To demo, run

- `python manage.py runserver 8080`, or
- `uvicorn src.asgi:application`

and go to http://127.0.0.1:8080.
20 changes: 20 additions & 0 deletions examples/async-views/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#!/usr/bin/env python
import os
import sys


def main() -> None:
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
'available on your PYTHONPATH environment variable? Did you '
'forget to activate a virtual environment?'
) from exc
execute_from_command_line(sys.argv)


if __name__ == '__main__':
main()
File renamed without changes.
7 changes: 7 additions & 0 deletions examples/async-views/src/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import os

from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'src.settings')

application = get_asgi_application()
12 changes: 12 additions & 0 deletions examples/async-views/src/services.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import asyncio
import logging
from random import randint

logger = logging.getLogger(__name__)


async def some_async_function() -> int:
logger.info('Doing i/o bound work')
await asyncio.sleep(1)
logger.warning('Finished i/o bound work')
return randint(0, 10)
116 changes: 116 additions & 0 deletions examples/async-views/src/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import os
from typing import List

# fmt: off

# No values are required
DJANGO_GUID = {
'GUID_HEADER_NAME': 'X-Request-ID',
'VALIDATE_GUID': False,
}

# Log filter setup is required
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'correlation_id': {'()': 'django_guid.log_filters.CorrelationId'}, # <-- Add correlation ID
},
'formatters': {
# Example of a basic log format without correlation ID filter
'basic_format': {'format': '%(levelname)s %(asctime)s %(name)s - %(message)s'},

# Example format with correlation ID
'correlation_id': {
'format': '%(levelname)s %(asctime)s [%(correlation_id)s] %(name)s - %(message)s' # <-- Add the %(correlation_id)s
},
},
'handlers': {
'correlation_id_handler': {
'class': 'logging.StreamHandler',
'formatter': 'correlation_id',
'filters': ['correlation_id'], # <-- Add this filter here
},
},
'loggers': {
'django': {
'handlers': ['correlation_id_handler'], # <-- Add the handler in your loggers
'level': 'INFO'
},
'src': {
'handlers': ['correlation_id_handler'],
'level': 'DEBUG'
},
'django_guid': {
'handlers': ['correlation_id_handler'],
'level': 'DEBUG',
'propagate': True,
},
}
}

# fmt: on


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

SECRET_KEY = 'secret'

DEBUG = True

ALLOWED_HOSTS: List[str] = []

# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'django_guid',
]

MIDDLEWARE = [
'django_guid.middleware.guid_middleware', # <-- Add middleware at the top of your middlewares
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'src.urls'

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'NAME': ':memory:',
}
}
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
5 changes: 5 additions & 0 deletions examples/async-views/src/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.urls import path

from . import views

urlpatterns = [path('', views.index_view, name='index')]
20 changes: 20 additions & 0 deletions examples/async-views/src/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import asyncio
import logging
from typing import TYPE_CHECKING

from django.http import JsonResponse

from .services import some_async_function

if TYPE_CHECKING:
from django.http import HttpRequest

logger = logging.getLogger(__name__)


async def index_view(request: 'HttpRequest') -> JsonResponse:
logger.info('Fetching counts asynchronously')
counts = await asyncio.gather(
asyncio.create_task(some_async_function()), asyncio.create_task(some_async_function())
)
return JsonResponse({'sum': sum(counts)})
Loading

0 comments on commit 38b9c22

Please sign in to comment.