diff --git a/.gitignore b/.gitignore index 2cc389249..32645c080 100755 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ *.egg-info *.pyc *.so +*.sqlite3 .coverage .pytest_cache .tox diff --git a/examples/frameworks/django/README b/examples/frameworks/django/README deleted file mode 100644 index 52841a2da..000000000 --- a/examples/frameworks/django/README +++ /dev/null @@ -1,3 +0,0 @@ -Applications to test Django support: - -testing -> Django 1.4 diff --git a/examples/frameworks/django/testing/testing/apps/someapp/__init__.py b/examples/frameworks/django/testing/testing/apps/someapp/__init__.py deleted file mode 100755 index e69de29bb..000000000 diff --git a/examples/frameworks/django/testing/testing/apps/someapp/middleware.py b/examples/frameworks/django/testing/testing/apps/someapp/middleware.py deleted file mode 100644 index ddc667a90..000000000 --- a/examples/frameworks/django/testing/testing/apps/someapp/middleware.py +++ /dev/null @@ -1,23 +0,0 @@ -from multiprocessing import Process, Queue -import requests - - -def child_process(queue): - while True: - print(queue.get()) - requests.get('http://requestb.in/15s95oz1') - - -class GunicornSubProcessTestMiddleware(object): - def __init__(self): - super().__init__() - self.queue = Queue() - self.process = Process(target=child_process, args=(self.queue,)) - self.process.start() - - def process_request(self, request): - self.queue.put(('REQUEST',)) - - def process_response(self, request, response): - self.queue.put(('RESPONSE', response.status_code)) - return response diff --git a/examples/frameworks/django/testing/testing/apps/someapp/templates/base.html b/examples/frameworks/django/testing/testing/apps/someapp/templates/base.html deleted file mode 100644 index 3470b71d4..000000000 --- a/examples/frameworks/django/testing/testing/apps/someapp/templates/base.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - gunicorn django example app - - - - -
-

test app

-
- - {% block content %}{% endblock %} - - - - - - diff --git a/examples/frameworks/django/testing/testing/apps/someapp/templates/home.html b/examples/frameworks/django/testing/testing/apps/someapp/templates/home.html deleted file mode 100644 index 3a8cc44b4..000000000 --- a/examples/frameworks/django/testing/testing/apps/someapp/templates/home.html +++ /dev/null @@ -1,18 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -
- {% csrf_token %} - - {{ form.as_table }} -
- -
- -

Got

- {% if subject %} -

subject:
{{ subject}}

-

message:
{{ message }}

-

size:
{{ size }}

- {% endif %} -{% endblock content %} diff --git a/examples/frameworks/django/testing/testing/apps/someapp/urls.py b/examples/frameworks/django/testing/testing/apps/someapp/urls.py deleted file mode 100644 index c1a482635..000000000 --- a/examples/frameworks/django/testing/testing/apps/someapp/urls.py +++ /dev/null @@ -1,8 +0,0 @@ -from django.conf.urls import url - -from . import views - -urlpatterns = [ - url(r'^acsv$', views.acsv), - url(r'^$', views.home), -] diff --git a/examples/frameworks/django/testing/testing/apps/someapp/views.py b/examples/frameworks/django/testing/testing/apps/someapp/views.py deleted file mode 100755 index abf775458..000000000 --- a/examples/frameworks/django/testing/testing/apps/someapp/views.py +++ /dev/null @@ -1,66 +0,0 @@ -import csv -import io -import os -from django import forms -from django.http import HttpResponse -from django.shortcuts import render -from django.template import RequestContext - - -class MsgForm(forms.Form): - subject = forms.CharField(max_length=100) - message = forms.CharField() - f = forms.FileField() - - -def home(request): - from django.conf import settings - print(settings.SOME_VALUE) - subject = None - message = None - size = 0 - print(request.META) - if request.POST: - form = MsgForm(request.POST, request.FILES) - print(request.FILES) - if form.is_valid(): - subject = form.cleaned_data['subject'] - message = form.cleaned_data['message'] - f = request.FILES['f'] - - if not hasattr(f, "fileno"): - size = len(f.read()) - else: - try: - size = int(os.fstat(f.fileno())[6]) - except io.UnsupportedOperation: - size = len(f.read()) - else: - form = MsgForm() - - - - return render(request, 'home.html', { - 'form': form, - 'subject': subject, - 'message': message, - 'size': size - }) - - -def acsv(request): - rows = [ - {'a': 1, 'b': 2}, - {'a': 3, 'b': 3} - ] - - response = HttpResponse(mimetype='text/csv') - response['Content-Disposition'] = 'attachment; filename=report.csv' - - writer = csv.writer(response) - writer.writerow(['a', 'b']) - - for r in rows: - writer.writerow([r['a'], r['b']]) - - return response diff --git a/examples/frameworks/django/testing/testing/settings.py b/examples/frameworks/django/testing/testing/settings.py deleted file mode 100644 index a26eaa76a..000000000 --- a/examples/frameworks/django/testing/testing/settings.py +++ /dev/null @@ -1,172 +0,0 @@ -# Django settings for testing project. - -DEBUG = True -TEMPLATE_DEBUG = DEBUG - -ADMINS = ( - # ('Your Name', 'your_email@example.com'), -) - -MANAGERS = ADMINS - -DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. - 'NAME': 'testdb.sql', # Or path to database file if using sqlite3. - 'USER': '', # Not used with sqlite3. - 'PASSWORD': '', # Not used with sqlite3. - 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. - 'PORT': '', # Set to empty string for default. Not used with sqlite3. - } -} - -# Local time zone for this installation. Choices can be found here: -# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name -# although not all choices may be available on all operating systems. -# On Unix systems, a value of None will cause Django to use the same -# timezone as the operating system. -# If running in a Windows environment this must be set to the same as your -# system time zone. -TIME_ZONE = 'America/Chicago' - -# Language code for this installation. All choices can be found here: -# http://www.i18nguy.com/unicode/language-identifiers.html -LANGUAGE_CODE = 'en-us' - -SITE_ID = 1 - -# If you set this to False, Django will make some optimizations so as not -# to load the internationalization machinery. -USE_I18N = True - -# If you set this to False, Django will not format dates, numbers and -# calendars according to the current locale. -USE_L10N = True - -# If you set this to False, Django will not use timezone-aware datetimes. -USE_TZ = True - -# Absolute filesystem path to the directory that will hold user-uploaded files. -# Example: "/home/media/media.lawrence.com/media/" -MEDIA_ROOT = '' - -# URL that handles the media served from MEDIA_ROOT. Make sure to use a -# trailing slash. -# Examples: "http://media.lawrence.com/media/", "http://example.com/media/" -MEDIA_URL = '' - -# Absolute path to the directory static files should be collected to. -# Don't put anything in this directory yourself; store your static files -# in apps' "static/" subdirectories and in STATICFILES_DIRS. -# Example: "/home/media/media.lawrence.com/static/" -STATIC_ROOT = '' - -# URL prefix for static files. -# Example: "http://media.lawrence.com/static/" -STATIC_URL = '/static/' - -# Additional locations of static files -STATICFILES_DIRS = ( - # Put strings here, like "/home/html/static" or "C:/www/django/static". - # Always use forward slashes, even on Windows. - # Don't forget to use absolute paths, not relative paths. -) - -# List of finder classes that know how to find static files in -# various locations. -STATICFILES_FINDERS = ( - 'django.contrib.staticfiles.finders.FileSystemFinder', - 'django.contrib.staticfiles.finders.AppDirectoriesFinder', -# 'django.contrib.staticfiles.finders.DefaultStorageFinder', -) - -# Make this unique, and don't share it with anybody. -SECRET_KEY = 'what' - - -# List of callables that know how to import templates from various sources. -TEMPLATE_LOADERS = ( - 'django.template.loaders.filesystem.Loader', - 'django.template.loaders.app_directories.Loader', -# 'django.template.loaders.eggs.Loader', -) - -MIDDLEWARE_CLASSES = ( - 'django.middleware.common.CommonMiddleware', - 'django.contrib.sessions.middleware.SessionMiddleware', - 'django.middleware.csrf.CsrfViewMiddleware', - 'django.contrib.auth.middleware.AuthenticationMiddleware', - 'django.contrib.messages.middleware.MessageMiddleware', - # Uncomment the next line for simple clickjacking protection: - # 'django.middleware.clickjacking.XFrameOptionsMiddleware', - # uncomment the next line to test multiprocessing - #'testing.apps.someapp.middleware.GunicornSubProcessTestMiddleware', -) - -ROOT_URLCONF = 'testing.urls' - -# Python dotted path to the WSGI application used by Django's runserver. -WSGI_APPLICATION = 'testing.wsgi.application' - -TEMPLATES = [ - { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], - 'APP_DIRS': True, - 'OPTIONS': { - # ... some options here ... - }, - }, -] - -TEMPLATE_DIRS = ( - # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". - # Always use forward slashes, even on Windows. - # Don't forget to use absolute paths, not relative paths. -) - -INSTALLED_APPS = ( - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.sites', - 'django.contrib.messages', - 'django.contrib.staticfiles', - # Uncomment the next line to enable the admin: - 'django.contrib.admin', - # Uncomment the next line to enable admin documentation: - # 'django.contrib.admindocs', - 'testing.apps.someapp', - 'gunicorn' -) - -# A sample logging configuration. The only tangible logging -# performed by this configuration is to send an email to -# the site admins on every HTTP 500 error when DEBUG=False. -# See http://docs.djangoproject.com/en/dev/topics/logging for -# more details on how to customize your logging configuration. -LOGGING = { - 'version': 1, - 'disable_existing_loggers': False, - 'filters': { - 'require_debug_false': { - '()': 'django.utils.log.RequireDebugFalse' - } - }, - 'handlers': { - 'mail_admins': { - 'level': 'ERROR', - 'filters': ['require_debug_false'], - 'class': 'django.utils.log.AdminEmailHandler' - } - }, - 'loggers': { - 'django.request': { - 'handlers': ['mail_admins'], - 'level': 'ERROR', - 'propagate': True, - }, - } -} - -SOME_VALUE = "test on reload" diff --git a/examples/frameworks/django/testing/testing/urls.py b/examples/frameworks/django/testing/testing/urls.py deleted file mode 100644 index bb95bf065..000000000 --- a/examples/frameworks/django/testing/testing/urls.py +++ /dev/null @@ -1,19 +0,0 @@ -from django.conf.urls import include, url - -# Uncomment the next two lines to enable the admin: -from django.contrib import admin -admin.autodiscover() - -urlpatterns = [ - # Examples: - # url(r'^$', 'testing.views.home', name='home'), - # url(r'^testing/', include('testing.foo.urls')), - - # Uncomment the admin/doc line below to enable admin documentation: - # url(r'^admin/doc/', include('django.contrib.admindocs.urls')), - - # Uncomment the next line to enable the admin: - url(r'^admin/', admin.site.urls), - - url(r'^', include("testing.apps.someapp.urls")), -] diff --git a/examples/frameworks/django/testing/testing/wsgi.py b/examples/frameworks/django/testing/testing/wsgi.py deleted file mode 100644 index 5be3fb9c8..000000000 --- a/examples/frameworks/django/testing/testing/wsgi.py +++ /dev/null @@ -1,34 +0,0 @@ -""" -WSGI config for testing project. - -This module contains the WSGI application used by Django's development server -and any production WSGI deployments. It should expose a module-level variable -named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover -this application via the ``WSGI_APPLICATION`` setting. - -Usually you will have the standard Django WSGI application here, but it also -might make sense to replace the whole Django WSGI application with a custom one -that later delegates to the Django one. For example, you could introduce WSGI -middleware here, or combine a Django application with an application of another -framework. - -""" -import os -import sys - -# make sure the current project is in PYTHONPATH -sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), - ".."))) - -# set the environment settings -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testing.settings") - -# This application object is used by any WSGI server configured to use this -# file. This includes Django's development server, if the WSGI_APPLICATION -# setting points here. -from django.core.wsgi import get_wsgi_application -application = get_wsgi_application() - -# Apply WSGI middleware here. -# from helloworld.wsgi import HelloWorldApplication -# application = HelloWorldApplication(application) diff --git a/examples/frameworks/django/testing/testing/__init__.py b/examples/frameworks/django_project/django_project/__init__.py similarity index 100% rename from examples/frameworks/django/testing/testing/__init__.py rename to examples/frameworks/django_project/django_project/__init__.py diff --git a/examples/frameworks/django_project/django_project/asgi.py b/examples/frameworks/django_project/django_project/asgi.py new file mode 100644 index 000000000..a3c334fb2 --- /dev/null +++ b/examples/frameworks/django_project/django_project/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for django_project project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") + +application = get_asgi_application() diff --git a/examples/frameworks/django_project/django_project/settings.py b/examples/frameworks/django_project/django_project/settings.py new file mode 100644 index 000000000..ee0bc17fb --- /dev/null +++ b/examples/frameworks/django_project/django_project/settings.py @@ -0,0 +1,154 @@ +""" +Django settings for django_project project. + +Generated by 'django-admin startproject' using Django 4.2.11. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +import secrets +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = "django-insecure-%s" % (secrets.token_urlsafe(32)) + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True +TEMPLATE_DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "someapp", +] + +MIDDLEWARE = [ + "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", + # multiprocessing test + "someapp.middleware.GunicornSubProcessTestMiddleware", +] + +ROOT_URLCONF = "django_project.urls" + +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", + ], + }, + }, +] + +WSGI_APPLICATION = "django_project.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", + }, + { + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.2/topics/i18n/ + +LANGUAGE_CODE = "en-us" + +TIME_ZONE = "UTC" + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.2/howto/static-files/ + +STATIC_URL = "static/" + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + +# performed by this configuration is to send an email to +# the site admins on every HTTP 500 error when DEBUG=False. +# See http://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. +LOGGING = { + "version": 1, + "disable_existing_loggers": False, + "filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}}, + "handlers": { + "mail_admins": { + "level": "ERROR", + "filters": ["require_debug_false"], + "class": "django.utils.log.AdminEmailHandler", + } + }, + "loggers": { + "django.request": { + "handlers": ["mail_admins"], + "level": "ERROR", + "propagate": True, + }, + }, +} + +SOME_VALUE = "test on reload" diff --git a/examples/frameworks/django_project/django_project/urls.py b/examples/frameworks/django_project/django_project/urls.py new file mode 100644 index 000000000..0559c3a10 --- /dev/null +++ b/examples/frameworks/django_project/django_project/urls.py @@ -0,0 +1,23 @@ +""" +URL configuration for django_project project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import include, path + +urlpatterns = [ + path("admin/", admin.site.urls), + path("", include("someapp.urls")), +] diff --git a/examples/frameworks/django_project/django_project/wsgi.py b/examples/frameworks/django_project/django_project/wsgi.py new file mode 100644 index 000000000..1e5bb4be9 --- /dev/null +++ b/examples/frameworks/django_project/django_project/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for django_project project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") + +application = get_wsgi_application() diff --git a/examples/frameworks/django/testing/manage.py b/examples/frameworks/django_project/manage.py similarity index 61% rename from examples/frameworks/django/testing/manage.py rename to examples/frameworks/django_project/manage.py index 156404496..b8d1bffc6 100755 --- a/examples/frameworks/django/testing/manage.py +++ b/examples/frameworks/django_project/manage.py @@ -1,8 +1,9 @@ #!/usr/bin/env python -import os, sys +import os +import sys if __name__ == "__main__": - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testing.settings") + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_project.settings") from django.core.management import execute_from_command_line diff --git a/examples/frameworks/django/testing/testing/apps/__init__.py b/examples/frameworks/django_project/someapp/__init__.py similarity index 100% rename from examples/frameworks/django/testing/testing/apps/__init__.py rename to examples/frameworks/django_project/someapp/__init__.py diff --git a/examples/frameworks/django_project/someapp/apps.py b/examples/frameworks/django_project/someapp/apps.py new file mode 100644 index 000000000..9a291de78 --- /dev/null +++ b/examples/frameworks/django_project/someapp/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class SomeappConfig(AppConfig): + name = "someapp" diff --git a/examples/frameworks/django_project/someapp/middleware.py b/examples/frameworks/django_project/someapp/middleware.py new file mode 100644 index 000000000..d14ad7fa0 --- /dev/null +++ b/examples/frameworks/django_project/someapp/middleware.py @@ -0,0 +1,25 @@ +import os +import time +from multiprocessing import Process, Queue + + +def child_process(queue): + # import requests + while True: + print(*queue.get()) + # requests.get('https://requestb.invalid/15s95oz1') + + +class GunicornSubProcessTestMiddleware: + def __init__(self, get_response): + super().__init__() + self.get_response = get_response + self.queue = Queue() + self.process = Process(target=child_process, args=(self.queue,)) + self.process.start() + + def __call__(self, request): + self.queue.put(("REQUEST",)) + response = self.get_response(request) + self.queue.put(("RESPONSE", response.status_code)) + return response diff --git a/examples/frameworks/django/testing/testing/apps/someapp/models.py b/examples/frameworks/django_project/someapp/models.py similarity index 100% rename from examples/frameworks/django/testing/testing/apps/someapp/models.py rename to examples/frameworks/django_project/someapp/models.py diff --git a/examples/frameworks/django_project/someapp/templates/base.html b/examples/frameworks/django_project/someapp/templates/base.html new file mode 100644 index 000000000..bc5fb5141 --- /dev/null +++ b/examples/frameworks/django_project/someapp/templates/base.html @@ -0,0 +1,17 @@ + + + + + gunicorn django example app + + +
+

test app

+
+ + {% block content %}{% endblock %} + + + + + diff --git a/examples/frameworks/django_project/someapp/templates/home.html b/examples/frameworks/django_project/someapp/templates/home.html new file mode 100644 index 000000000..c9844193a --- /dev/null +++ b/examples/frameworks/django_project/someapp/templates/home.html @@ -0,0 +1,17 @@ +{% extends "base.html" %} + +{% block content %} +
+ {% csrf_token %} + {{ form.as_div }} + +
+ +

Got

+ {% if subject %} +

subject:
{{ subject}}

+

message:
{{ message }}

+

file name:
{{ fname }}

+

file size:
{{ fsize }}

+ {% endif %} +{% endblock content %} diff --git a/examples/frameworks/django/testing/testing/apps/someapp/tests.py b/examples/frameworks/django_project/someapp/tests.py old mode 100755 new mode 100644 similarity index 92% rename from examples/frameworks/django/testing/testing/apps/someapp/tests.py rename to examples/frameworks/django_project/someapp/tests.py index 85c920bb8..f51d798ff --- a/examples/frameworks/django/testing/testing/apps/someapp/tests.py +++ b/examples/frameworks/django_project/someapp/tests.py @@ -7,6 +7,7 @@ from django.test import TestCase + class SimpleTest(TestCase): def test_basic_addition(self): """ @@ -14,9 +15,12 @@ def test_basic_addition(self): """ self.assertEqual(1 + 1, 2) -__test__ = {"doctest": """ + +__test__ = { + "doctest": """ Another way to test that 1 + 1 is equal to 2. >>> 1 + 1 == 2 True -"""} +""" +} diff --git a/examples/frameworks/django_project/someapp/urls.py b/examples/frameworks/django_project/someapp/urls.py new file mode 100644 index 000000000..2e90ca4d8 --- /dev/null +++ b/examples/frameworks/django_project/someapp/urls.py @@ -0,0 +1,8 @@ +from django.urls import path + +from . import views + +urlpatterns = [ + path("acsv", views.acsv), + path("", views.home), +] diff --git a/examples/frameworks/django_project/someapp/views.py b/examples/frameworks/django_project/someapp/views.py new file mode 100644 index 000000000..17d78b9c3 --- /dev/null +++ b/examples/frameworks/django_project/someapp/views.py @@ -0,0 +1,62 @@ +import csv +import io +import os + +from django import forms +from django.conf import settings +from django.http import HttpResponse +from django.shortcuts import render +from django.template import RequestContext + + +class MsgForm(forms.Form): + subject = forms.CharField(max_length=100) + message = forms.CharField() + f = forms.FileField() + + +def home(request): + print("SETTING", settings.SOME_VALUE) + subject = None + message = None + fname = None + fsize = 0 + print("META", request.META) + if request.POST: + form = MsgForm(request.POST, request.FILES) + print("FILES", request.FILES) + if form.is_valid(): + subject = form.cleaned_data["subject"] + message = form.cleaned_data["message"] + f = request.FILES["f"] + fsize = f.size + fname = f.name + else: + form = MsgForm() + + return render( + request, + "home.html", + { + "form": form, + "subject": subject, + "message": message, + "fsize": fsize, + "fname": fname, + }, + ) + + +def acsv(request): + rows = [{"a": 1, "b": 2}, {"a": 3, "b": 3}] + + response = HttpResponse(mimetype="text/csv") + response["Content-Disposition"] = "attachment; filename=report.csv" + + writer = csv.writer(response) + writer.writerow(["a", "b"]) + + for r in rows: + writer.writerow([r["a"], r["b"]]) + + return response