Permalink
Browse files

Upgrade demoproject to use Django 1.4 template

  • Loading branch information...
1 parent 077b288 commit e60de28dea85001ec0140f9a3ea0dbfcbfb76763 @ask committed Apr 12, 2012
View
@@ -18,3 +18,6 @@ def setup_loader():
# Importing this module enables the Celery Django loader.
setup_loader()
+
+
+from celery import current_app as celery
@@ -1,62 +0,0 @@
-from collections import defaultdict
-
-import cl
-
-from celery import current_app as celery
-from celery.utils.timer2 import apply_interval
-
-
-from clickmuncher import models
-
-
-class Clicks(cl.Actor):
- default_routing_key = "Clicks"
-
- class state:
- model = models.Click
- clicks = defaultdict(lambda: 0)
-
- def increment(self, url, clicks=1):
- self.clicks[url] += clicks
-
- def flush(self):
- print("FLUSH!!!")
- print("STATE: %r" % (self.clicks, ))
- for url, clicks in self.clicks.iteritems():
- self.model.objects.increment_clicks(url, clicks)
- self.clicks.clear()
-
- def __init__(self, connection=None, *args, **kwargs):
- if not connection:
- connection = celery.broker_connection()
- super(Clicks, self).__init__(connection, *args, **kwargs)
-
- def increment(self, url, clicks=1):
- self.cast("increment", {"url": url, "clicks": clicks})
-
-
-class Agent(cl.Agent):
- actors = [Clicks()]
- flush_every = 5
-
- def __init__(self, connection=None, *args, **kwargs):
- if not connection:
- connection = celery.broker_connection()
- self.clicks = Clicks()
- self.actors = [self.clicks]
- self.timers = []
- super(Agent, self).__init__(connection, *args, **kwargs)
-
- def on_consume_ready(self, *args, **kwargs):
- print("INSTALLING TIMER")
- self.timers.append(apply_interval(self.flush_every * 1000,
- self.clicks.state.flush))
-
- def stop(self):
- for entry in self.timers:
- entry.cancel()
- super(Agent, self).stop()
-
-
-if __name__ == "__main__":
- Agent().run_from_commandline()
@@ -1,27 +0,0 @@
-from django.db import models
-from django.utils.translation import ugettext_lazy as _
-from djcelery.managers import ExtendedManager
-
-
-class ClickManager(ExtendedManager):
-
- def increment_clicks(self, url, increment=1):
- """Increment the click count for an URL."""
- obj, created = self.get_or_create(url=url,
- defaults={"clicks": increment})
- if not created:
- obj.clicks += increment
- obj.save()
-
- return obj.clicks
-
-
-class Click(models.Model):
- url = models.URLField(_(u"URL"), verify_exists=False, unique=True)
- clicks = models.PositiveIntegerField(_(u"clicks"), default=0)
-
- objects = ClickManager()
-
- class Meta:
- verbose_name = _(u"click")
- verbose_name_plural = _(u"clicks")
@@ -1,14 +0,0 @@
-#!/usr/bin/env python
-from django.core.management import execute_manager
-import imp
-try:
- imp.find_module('settings') # Assumed to be in the same directory.
-except ImportError:
- import sys
- sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n" % __file__)
- sys.exit(1)
-
-import settings
-
-if __name__ == "__main__":
- execute_manager(settings)
@@ -1,17 +0,0 @@
-from django.conf.urls import patterns, include, url
-
-# Uncomment the next two lines to enable the admin:
-# from django.contrib import admin
-# admin.autodiscover()
-
-urlpatterns = patterns('',
- # Examples:
- # url(r'^$', 'clickcounter.views.home', name='home'),
- # url(r'^clickcounter/', include('clickcounter.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)),
-)
No changes.
@@ -1,4 +1,3 @@
-# All Django apps must have a models.py.
-from django.db import models # noqa
+from django.db import models
# Create your models here.
@@ -1,18 +1,18 @@
-from celery.task import task
+from djcelery import celery
-@task
+@celery.task
def add(x, y):
return x + y
-@task
+@celery.task
def sleeptask(i):
from time import sleep
sleep(i)
return i
-@task
+@celery.task
def raisetask():
raise KeyError("foo")
@@ -0,0 +1,16 @@
+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+ def test_basic_addition(self):
+ """
+ Tests that 1 + 1 always equals 2.
+ """
+ self.assertEqual(1 + 1, 2)
@@ -1,8 +1,9 @@
# Create your views here.
-from demoapp import tasks
from django.http import HttpResponse
+from demoapp import tasks
+
def foo(request):
r = tasks.add.delay(2, 2)
@@ -1,11 +1,36 @@
-# Django settings for clickcounter project.
+# Django settings for demoproject project.
+# -- Celery related configuration
import djcelery
djcelery.setup_loader()
-import os
-import sys
-sys.path.append(os.getcwd())
+
+BROKER_URL = "amqp://guest:guest@localhost:5672//"
+CELERY_RESULT_BACKEND = "database"
+
+# -- other necessary settings.
+
+DATABASES = {"default": {"NAME": "testdb.sqlite",
+ "ENGINE": "django.db.backends.sqlite3",
+ "USER": '',
+ "PASSWORD": '',
+ "HOST": '',
+ "PORT": ''}}
+
+
+INSTALLED_APPS = (
+ 'django.contrib.auth',
+ 'django.contrib.contenttypes',
+ 'django.contrib.sessions',
+ 'django.contrib.sites',
+ 'django.contrib.messages',
+ 'django.contrib.staticfiles',
+ 'django.contrib.admin',
+ 'djcelery',
+ 'demoapp',
+)
+
+# -- rest is from Django 1.4 template
DEBUG = True
TEMPLATE_DEBUG = DEBUG
@@ -16,17 +41,6 @@
MANAGERS = ADMINS
-DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': 'test.db',
- 'USER': '',
- 'PASSWORD': '',
- 'HOST': '',
- 'PORT': '',
- }
-}
-
# 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.
@@ -47,9 +61,12 @@
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
-# calendars according to the current locale
+# 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 = ''
@@ -85,7 +102,7 @@
)
# Make this unique, and don't share it with anybody.
-SECRET_KEY = '(up^8#vyl9fj+x4_o!5!-h-u-ydixwxb!pih)%5j#jsj2btir9'
+SECRET_KEY = 'utpl%umodw@pb=t3v8e6c8+)f&ra41gon9l&5+3566nr88%b3y'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
@@ -104,26 +121,17 @@
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
-ROOT_URLCONF = 'clickcounter.urls'
+ROOT_URLCONF = 'demoproject.urls'
+
+# Python dotted path to the WSGI application used by Django's runserver.
+WSGI_APPLICATION = 'demoproject.wsgi.application'
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',
- 'djcelery',
-
- 'clickmuncher',
-)
-
# 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.
@@ -0,0 +1,28 @@
+"""
+WSGI config for demoproject 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
+
+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.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)
@@ -1,15 +1,10 @@
#!/usr/bin/env python
-from django.core.management import execute_manager
-try:
- import settings # Assumed to be in the same directory.
-except ImportError:
- import sys
- sys.stderr.write("""Error: Can't find the file 'settings.py' in the \
- directory containing %r. It appears you've customized things.
- You'll have to run django-admin.py, passing it your settings module.
- (If the file settings.py does indeed exist, it's causing an
- ImportError somehow.)\n""" % __file__)
- sys.exit(1)
+import os
+import sys
if __name__ == "__main__":
- execute_manager(settings)
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demoproject.settings")
+
+ from django.core.management import execute_from_command_line
+
+ execute_from_command_line(sys.argv)
Oops, something went wrong.

0 comments on commit e60de28

Please sign in to comment.