Browse Source

Improved Django settings and syntax (#4951)

Anthony Monthe 6 years ago
parent
commit
f79f22000e

+ 6 - 85
frameworks/Python/django/hello/hello/settings.py

@@ -1,13 +1,9 @@
-# Django settings for hello project.
-
 import os
 import os
 
 
 DEBUG = False
 DEBUG = False
 
 
-
-ADMINS = (
-    # ('Your Name', '[email protected]'),
-)
+SECRET_KEY = '_7mb6#v4yf@qhc(r(zbyh&z_iby-na*7wz&-v6pohsul-d#y5f'
+ADMINS = ()
 
 
 MANAGERS = ADMINS
 MANAGERS = ADMINS
 
 
@@ -23,113 +19,38 @@ DATABASES = {
     }
     }
 }
 }
 
 
-# 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'
 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'
 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 = False
 USE_I18N = False
-
-# If you set this to False, Django will not format dates, numbers and
-# calendars according to the current locale.
 USE_L10N = False
 USE_L10N = False
-
-# If you set this to False, Django will not use timezone-aware datetimes.
 USE_TZ = False
 USE_TZ = False
 
 
-# Absolute filesystem path to the directory that will hold user-uploaded files.
-# Example: "/home/media/media.lawrence.com/media/"
 MEDIA_ROOT = ''
 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 = ''
 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 = ''
 STATIC_ROOT = ''
-
-# URL prefix for static files.
-# Example: "http://media.lawrence.com/static/"
 STATIC_URL = '/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 = '_7mb6#v4yf@qhc(r(zbyh&z_iby-na*7wz&-v6pohsul-d#y5f'
-
-
-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',
-)
+STATICFILES_DIRS = ()
+STATICFILES_FINDERS = ()
+MIDDLEWARE = ()
 
 
 ROOT_URLCONF = 'hello.urls'
 ROOT_URLCONF = 'hello.urls'
-
-# Python dotted path to the WSGI application used by Django's runserver.
 WSGI_APPLICATION = 'hello.wsgi.application'
 WSGI_APPLICATION = 'hello.wsgi.application'
 
 
-
 TEMPLATES = [
 TEMPLATES = [
     {
     {
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
         'BACKEND': 'django.template.backends.django.DjangoTemplates',
         'DIRS': [],
         'DIRS': [],
         'APP_DIRS': True,
         'APP_DIRS': True,
-        'OPTIONS': {
-        },
+        'OPTIONS': {},
     },
     },
 ]
 ]
 
 
 INSTALLED_APPS = (
 INSTALLED_APPS = (
-    'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.contenttypes',
     'django.contrib.sessions',
     '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',
     'world',
     'world',
 )
 )
 
 
-# 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 = {
 LOGGING = {
     'version': 1,
     'version': 1,
     'disable_existing_loggers': True,
     'disable_existing_loggers': True,

+ 0 - 14
frameworks/Python/django/hello/hello/urls.py

@@ -1,21 +1,7 @@
 from django.conf.urls import url
 from django.conf.urls import url
-
 from world.views import plaintext, json, db, dbs, fortunes, update
 from world.views import plaintext, json, db, dbs, fortunes, update
 
 
-# Uncomment the next two lines to enable the admin:
-# from django.contrib import admin
-# admin.autodiscover()
-
 urlpatterns = [
 urlpatterns = [
-    # Examples:
-    # url(r'^$', 'hello.views.home', name='home'),
-    # url(r'^hello/', include('hello.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/', include(admin.site.urls)),
     url(r'^plaintext$', plaintext),
     url(r'^plaintext$', plaintext),
     url(r'^json$', json),
     url(r'^json$', json),
     url(r'^db$', db),
     url(r'^db$', db),

+ 0 - 7
frameworks/Python/django/hello/hello/wsgi.py

@@ -17,12 +17,5 @@ import os
 
 
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hello.settings")
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hello.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
 from django.core.wsgi import get_wsgi_application
 application = get_wsgi_application()
 application = get_wsgi_application()
-
-# Apply WSGI middleware here.
-# from helloworld.wsgi import HelloWorldApplication
-# application = HelloWorldApplication(application)

+ 9 - 7
frameworks/Python/django/hello/world/models.py

@@ -1,13 +1,15 @@
 from django.db import models
 from django.db import models
 
 
-# Create your models here.
 
 
 class World(models.Model):
 class World(models.Model):
-  randomnumber = models.IntegerField()
-  class Meta:
-    db_table = 'world'
+    randomnumber = models.IntegerField()
+
+    class Meta:
+        db_table = 'world'
+
 
 
 class Fortune(models.Model):
 class Fortune(models.Model):
-  message = models.CharField(max_length=65535)
-  class Meta:
-    db_table = 'fortune'
+    message = models.CharField(max_length=65535)
+
+    class Meta:
+        db_table = 'fortune'

+ 61 - 54
frameworks/Python/django/hello/world/views.py

@@ -11,73 +11,80 @@ from world.models import World, Fortune
 
 
 
 
 if sys.version_info[0] == 3:
 if sys.version_info[0] == 3:
-  xrange = range
+    xrange = range
+
 
 
 def _get_queries(request):
 def _get_queries(request):
-  try:
-    queries = int(request.GET.get('queries', 1))
-  except Exception:
-    queries = 1
-  if queries < 1:
-    queries = 1
-  if queries > 500:
-    queries = 500
-  return queries
+    try:
+        queries = int(request.GET.get('queries', 1))
+    except Exception:
+        queries = 1
+    if queries < 1:
+        queries = 1
+    if queries > 500:
+        queries = 500
+    return queries
+
 
 
 def plaintext(request):
 def plaintext(request):
-  return HttpResponse("Hello, World!", content_type="text/plain")
+    return HttpResponse("Hello, World!", content_type="text/plain")
+
 
 
 def json(request):
 def json(request):
-  response = {
-    "message": "Hello, World!"
-  }
-  return HttpResponse(uj_dumps(response), content_type="application/json")
+    response = {
+        "message": "Hello, World!"
+    }
+    return HttpResponse(uj_dumps(response), content_type="application/json")
+
 
 
 def db(request):
 def db(request):
-  r = random.randint(1, 10000)
-  world = uj_dumps({'id' : r, 'randomNumber' : World.objects.get(id=r).randomnumber})
-  return HttpResponse(world, content_type="application/json")
+    r = random.randint(1, 10000)
+    world = uj_dumps({'id' : r, 'randomNumber' : World.objects.get(id=r).randomnumber})
+    return HttpResponse(world, content_type="application/json")
+
 
 
 def dbs(request):
 def dbs(request):
-  queries = _get_queries(request)
-
-  # fun fact:  every dot-notation lookup calls some python magic under the hood.  Like every other code,
-  # one can eliminate dereferences by storing the end dereferenced thing in an identifier
-  g = World.objects.get
-
-  # but wait!  there's more!  if we're calling a function over and over with the same parameters,
-  # we can use even more function magic.
-  #r = random.randint
-  rp = partial(random.randint, 1, 10000)
-
-  # now we're ready to write our awesome query iterator thingy
-  # first of all, we know the id's correspond to the random number we're picking, so we can create
-  # dictionaries on the fly instead of serializing later
-  # by creating dicts, we don't need to user the model serializer, which is probably slow and only appropriate
-  # for complicated serializations of joins and crazy query sets etc
-  # test xrange vs range if the query number is gigantic
-  worlds = uj_dumps([{'id' : r, 'randomNumber' : g(id=r).randomnumber} for r in [rp() for q in xrange(queries)]])
-  return HttpResponse(worlds, content_type="application/json")
+    queries = _get_queries(request)
+
+    # fun fact:    every dot-notation lookup calls some python magic under the hood.    Like every other code,
+    # one can eliminate dereferences by storing the end dereferenced thing in an identifier
+    g = World.objects.get
+
+    # but wait!    there's more!    if we're calling a function over and over with the same parameters,
+    # we can use even more function magic.
+    #r = random.randint
+    rp = partial(random.randint, 1, 10000)
+
+    # now we're ready to write our awesome query iterator thingy
+    # first of all, we know the id's correspond to the random number we're picking, so we can create
+    # dictionaries on the fly instead of serializing later
+    # by creating dicts, we don't need to user the model serializer, which is probably slow and only appropriate
+    # for complicated serializations of joins and crazy query sets etc
+    # test xrange vs range if the query number is gigantic
+    worlds = uj_dumps([{'id' : r, 'randomNumber' : g(id=r).randomnumber} for r in [rp() for q in xrange(queries)]])
+    return HttpResponse(worlds, content_type="application/json")
+
 
 
 def fortunes(request):
 def fortunes(request):
-  fortunes = list(Fortune.objects.all())
-  fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
+    fortunes = list(Fortune.objects.all())
+    fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
+
+    fortunes = sorted(fortunes, key=attrgetter('message'))
 
 
-  fortunes = sorted(fortunes, key=attrgetter('message'))
+    context = {'fortunes': fortunes}
+    return render(request, 'fortunes.html', context)
 
 
-  context = {'fortunes': fortunes}
-  return render(request, 'fortunes.html', context)
 
 
 def update(request):
 def update(request):
-  queries = _get_queries(request)
-  g = World.objects.get
-  rp = partial(random.randint, 1, 10000)
-
-  worlds = []
-  for r in [rp() for q in xrange(queries)]:
-    w = g(id=r)
-    w.randomnumber=rp()
-    w.save()
-    worlds.append({'id' : r, 'randomNumber' : w.randomnumber})
-
-  return HttpResponse(uj_dumps(worlds), content_type="application/json")
+    queries = _get_queries(request)
+    g = World.objects.get
+    rp = partial(random.randint, 1, 10000)
+
+    worlds = []
+    for r in [rp() for q in xrange(queries)]:
+        w = g(id=r)
+        w.randomnumber = rp()
+        w.save()
+        worlds.append({'id' : r, 'randomNumber' : w.randomnumber})
+
+    return HttpResponse(uj_dumps(worlds), content_type="application/json")