Permalink
Browse files

Updating to Django 1.4.2's new project structure and fixing imports f…

…or new structure.
  • Loading branch information...
1 parent a2df1f1 commit ef0e927800f03af3fd417a0c02981bd4d08de12e @klynton klynton committed Nov 13, 2012
View
No changes.
View
No changes.
View
No changes.
View
@@ -1,13 +0,0 @@
-from django import forms
-from images.services import ImageService
-
-
-class UploadForm(forms.Form):
- image = forms.ImageField()
-
- def save(self, request):
- if 'image' in request.FILES:
- file = request.FILES['image']
- image_service = ImageService()
- user_id = request.session['user_id']
- return image_service.store(file, user_id, file.content_type)
View
@@ -1,3 +0,0 @@
-from django.db import models
-
-# Create your models here.
View
@@ -1,133 +0,0 @@
-import sha
-import base64
-import uuid
-import httplib
-import re
-import shortuuid
-
-from urlparse import urlparse
-from datetime import datetime
-from PIL import Image
-from StringIO import StringIO
-from tempfile import NamedTemporaryFile
-from riak import RiakClient
-from django.conf import settings
-
-MAP_DOCID = """function(value) {
- var doc = Riak.mapValuesJson(value)[0];
- doc['id'] = value.key;
- return [doc];
- }"""
-
-
-class ImageError(Exception):
- pass
-
-
-class RemoteImage:
- def __init__(self, reader):
- self._temp_file = NamedTemporaryFile()
- print self._temp_file.name
- self._temp_file.write(reader.read())
- self._temp_file.seek(0)
-
- def temporary_file_path(self):
- return self._temp_file.name
-
- def read(self):
- return self._temp_file.read()
-
-
-class ImageService:
- def __init__(self):
- self.riak = RiakClient(host=settings.RIAK_HOST,
- port=settings.RIAK_PORT)
- self._metadata_bucket = self.riak.bucket(settings.RIAK_METADATA_BUCKET)
- self._image_bucket = self.riak.bucket(settings.RIAK_IMAGE_BUCKET)
- self._thumbs_bucket = self.riak.bucket(settings.RIAK_THUMBS_BUCKET)
-
- def store_from_url(self, address, user):
- url = urlparse(address)
- if str(url.scheme) != 'http':
- raise ImageError('Not a valid URL')
-
- if not re.search(r'(jpg|jpeg|png|gif)$', url.path):
- raise ImageError('Unsupported file format')
-
- http = httplib.HTTPConnection(url.netloc)
- http.request('GET', url.path)
- response = http.getresponse()
- image = RemoteImage(response)
- return self.store(image, user,
- response.getheader("Content-Type", "image/jpg"))
-
- def store(self, image, user, content_type):
- key = self.create_unique_key()
- filename = self.filename_for_image(key, content_type)
- data = {"user": user,
- "uploaded_at": datetime.utcnow().isoformat(),
- "filename": filename}
-
- thumbnail = self.create_thumbnail(image)
-
- metadata = self._metadata_bucket.new(key, data,
- content_type="application/json")
- metadata.store()
-
- image = self._image_bucket.new_binary(key, image.read(), content_type)
- image.store()
-
- thumb = self._thumbs_bucket.new_binary(key, thumbnail,
- content_type="image/jpeg")
- thumb.store()
-
- return key
-
- def create_thumbnail(self, image):
- thumbnail = Image.open(image.temporary_file_path())
- thumbnail.thumbnail((128, 128), Image.ANTIALIAS)
- thumbio = StringIO()
- thumbnail.save(thumbio, format="jpeg")
- return thumbio.getvalue()
-
- def find_metadata(self, image_id):
- image = self._metadata_bucket.get(image_id)
- if image.exists():
- return image.get_data()
- else:
- return None
-
- def find(self, image_id, thumb=False):
- if thumb:
- image = self._thumbs_bucket.get_binary(image_id)
- else:
- image = self._image_bucket.get_binary(image_id)
- if image.exists():
- return image
- else:
- return None
-
- def find_all(self, user):
- images = self.riak.search(settings.RIAK_METADATA_BUCKET,
- "user:%s" % user).map(MAP_DOCID).run()
- return images
-
- def create_unique_key(self, length=6):
- unique = False
- while not unique:
- id = self.unique_key(length)
- if not self._image_bucket.get(id).exists():
- return id
-
- def unique_key(self, length=6):
- return shortuuid.uuid()[0:length]
-
- def filename_for_image(self, key, content_type):
- if content_type in ['image/jpg', 'image/jpeg']:
- extension = 'jpg'
- elif content_type == "image/png":
- extension = 'png'
- elif content_type == 'image/gif':
- extension = 'gif'
-
- return "%s.%s" % (key, extension)
View
@@ -1,16 +0,0 @@
-"""
-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)
View
@@ -1,10 +0,0 @@
-from django.conf.urls.defaults import patterns, url
-
-urlpatterns = patterns('images.views',
- url(r'^upload$', 'upload'),
- url(r'^(?P<image_id>[a-zA-Z0-9]{5,6})$', 'show'),
- url(r'^(?P<image_id>[a-zA-Z0-9]{5,6})\.[a-z]{3}$', 'fetch'),
- url(r'^t/(?P<image_id>[a-zA-Z0-9]{5,6})\.[a-z]{3}$', 'fetch',
- {"thumb": True}),
- url(r'^mine$', 'mine')
-)
View
@@ -1,64 +0,0 @@
-from django.http import HttpResponse, HttpResponseRedirect, Http404
-from django.shortcuts import render_to_response, redirect, render
-from django.template import RequestContext
-
-from images.forms import UploadForm
-from images.services import ImageService, ImageError
-from users.service import UserService
-
-
-def upload(request):
- if request.method == "POST":
- upload = UploadForm(request.POST, request.FILES)
- filename = upload.save(request)
- if filename:
- return HttpResponseRedirect("/i/%s" % filename)
- else:
- user = None
- if 'user_id' in request.session:
- user_service = UserService()
- user = user_service.get(request.session['user_id'])
- return render(request, 'home.html',
- {"user": user, "upload_form": upload},
- context_instance=RequestContext(request))
- elif "url" in request.GET:
- image_service = ImageService()
- try:
- key = image_service.store_from_url(request.GET["url"],
- request.session["user_id"])
- return HttpResponseRedirect("/i/%s" % key)
- except ImageError as e:
- return HttpResponse(e.msg, status=400)
- else:
- return HttpResponseRedirect("/")
-
-
-def show(request, image_id):
- image_service = ImageService()
- image = image_service.find_metadata(str(image_id))
- if image:
- return render_to_response('images/show.html', {'image': image},
- context_instance=RequestContext(request))
- else:
- raise Http404
-
-
-def fetch(request, image_id, thumb=False):
- image_service = ImageService()
- image = image_service.find(str(image_id), thumb=thumb)
- if image:
- return HttpResponse(content=image.get_data(),
- mimetype=image.get_content_type())
- else:
- raise Http404
-
-
-def mine(request):
- if not 'user_id' in request.session:
- return redirect("/")
-
- user = request.session['user_id']
- image_service = ImageService()
- images = image_service.find_all(user)
- return render_to_response("images/mine.html", {'images': images},
- context_instance=RequestContext(request))
View
@@ -1,18 +1,10 @@
#!/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.\n"
- + "You'll have to run django-admin.py, passing it your "
- + "settings module.\n" % __file__)
- sys.exit(1)
-
-import settings
+import os
+import sys
if __name__ == "__main__":
- execute_manager(settings)
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "riagi.settings")
+
+ from django.core.management import execute_from_command_line
+
+ execute_from_command_line(sys.argv)
View
@@ -1,4 +1,4 @@
-Django==1.3
+Django==1.4.2
riak==1.5.1
PIL==1.1.7
shortuuid
View
@@ -1,109 +0,0 @@
-import os.path
-import riak
-import django_riak
-import pwd
-import os
-
-# Django settings for riagi project.
-
-if pwd.getpwuid(os.getuid())[0] == "dotcloud":
- RIAK_HOST = "riak01.riagi.com"
- RIAK_PORT = "8098"
- DEBUG = False
-else:
- RIAK_HOST = "127.0.0.1"
- RIAK_PORT = "8098"
- DEBUG = True
-
-TEMPLATE_DEBUG = DEBUG
-RIAK_PROTOCOL = "http"
-RIAK_USERS_BUCKET = "riagi-users"
-RIAK_IMAGE_BUCKET = "riagi-images"
-RIAK_THUMBS_BUCKET = "riagi-thumbs"
-RIAK_METADATA_BUCKET = "riagi-image-metadata"
-FILE_UPLOAD_MAX_MEMORY_SIZE = 0
-
-RIAK_TRANSPORT_CLASS = riak.RiakHttpTransport
-RIAK_BUCKET = 'django-riak-sessions'
-SESSION_ENGINE = "django_riak"
-APPEND_SLASH = False
-TIME_ZONE = 'Europe/London'
-# 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
-
-USE_I18N = False
-USE_L10N = False
-
-MEDIA_URL = ''
-STATIC_URL = '/static/'
-STATIC_ROOT = ''
-MEDIA_ROOT = ''
-
-STATICFILES_DIRS = (
- os.path.join(os.path.dirname(__file__), "static"),
-)
-
-STATICFILES_FINDERS = (
- 'django.contrib.staticfiles.finders.FileSystemFinder',
- 'django.contrib.staticfiles.finders.AppDirectoriesFinder',
-)
-
-SECRET_KEY = ')^)dn9@fe=7=7lurgj#$r9)h$1y9h*zc@kzdur46nd6l@qe%)!'
-
-TEMPLATE_LOADERS = (
- 'django.template.loaders.filesystem.Loader',
- 'django.template.loaders.app_directories.Loader',
-)
-
-MIDDLEWARE_CLASSES = (
- 'django.middleware.common.CommonMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
-)
-
-ROOT_URLCONF = 'urls'
-
-TEMPLATE_DIRS = (
- os.path.join(os.path.dirname(__file__), "templates")
-)
-
-INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'images',
- 'users'
- # Uncomment the next line to enable the admin:
- # 'django.contrib.admin',
- # Uncomment the next line to enable admin documentation:
- # 'django.contrib.admindocs',
-)
-
-TEMPLATE_CONTEXT_PROCESSORS = ("django.core.context_processors.debug",
-"django.core.context_processors.i18n", "django.core.context_processors.media",
-'django.core.context_processors.request',)
-
-LOGGING = {
- 'version': 1,
- 'disable_existing_loggers': False,
- 'handlers': {
- 'mail_admins': {
- 'level': 'ERROR',
- 'class': 'django.utils.log.AdminEmailHandler'
- }
- },
- 'loggers': {
- 'django.request': {
- 'handlers': ['mail_admins'],
- 'level': 'ERROR',
- 'propagate': True,
- },
- }
-}
Oops, something went wrong.

0 comments on commit ef0e927

Please sign in to comment.