Permalink
Browse files

Fix pep8 stuff, ignore virtualenv bits.

  • Loading branch information...
1 parent 6bebcc8 commit a2df1f146c2ee480d54a564734c11048deddf20d @seancribbs seancribbs committed Nov 12, 2012
Showing with 131 additions and 56 deletions.
  1. +4 −0 .gitignore
  2. +2 −1 README.md
  3. +8 −6 django_riak.py
  4. +0 −1 forms.py
  5. +1 −0 images/forms.py
  6. +23 −13 images/services.py
  7. +2 −1 images/urls.py
  8. +11 −3 images/views.py
  9. +6 −2 manage.py
  10. +1 −1 settings.py
  11. +32 −12 users/forms.py
  12. +17 −6 users/service.py
  13. +19 −8 users/views.py
  14. +5 −2 views.py
View
@@ -1 +1,5 @@
*.pyc
+.Python
+bin
+include
+lib
View
@@ -38,4 +38,5 @@ should see something like so:
## License
-riagi is licensed under the [Apache v2.0 license](/basho/riagi/blob/master/LICENSE).
+riagi is licensed under the
+[Apache v2.0 license](/basho/riagi/blob/master/LICENSE).
View
@@ -7,13 +7,15 @@
class SessionStore(SessionBase):
-
+
def __init__(self, session_key=None):
RIAK_PORT = getattr(settings, 'RIAK_PORT', 8087)
RIAK_HOST = getattr(settings, 'RIAK_HOST', "127.0.0.1")
- RIAK_TRANSPORT_CLASS = getattr(settings, 'RIAK_TRANSPORT_CLASS', riak.RiakPbcTransport)
+ RIAK_TRANSPORT_CLASS = getattr(settings, 'RIAK_TRANSPORT_CLASS',
+ riak.RiakPbcTransport)
RIAK_BUCKET = getattr(settings, 'RIAK_BUCKET', 'django-riak-sessions')
- self._client = riak.RiakClient(host=RIAK_HOST, port=RIAK_PORT, transport_class=RIAK_TRANSPORT_CLASS)
+ self._client = riak.RiakClient(host=RIAK_HOST, port=RIAK_PORT,
+ transport_class=RIAK_TRANSPORT_CLASS)
self._bucket = self._client.bucket(RIAK_BUCKET)
super(SessionStore, self).__init__(session_key)
@@ -37,8 +39,8 @@ def create(self):
continue
self.modified = True
return
-
- def save(self,must_create=True):
+
+ def save(self, must_create=True):
session_key = self.session_key
session_data = self.encode(self._get_session(no_load=must_create))
expire_date = time.mktime(self.get_expiry_date().timetuple())
@@ -52,7 +54,7 @@ def save(self,must_create=True):
def exists(self, session_key):
session = self._bucket.get(session_key)
return session.exists()
-
+
def delete(self, session_key=None):
sk = session_key
# Get the object and delete it if found.
View
@@ -1 +0,0 @@
-
View
@@ -1,6 +1,7 @@
from django import forms
from images.services import ImageService
+
class UploadForm(forms.Form):
image = forms.ImageField()
View
@@ -13,9 +13,17 @@
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()
@@ -25,13 +33,15 @@ def __init__(self, reader):
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.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)
@@ -48,7 +58,8 @@ def store_from_url(self, address, user):
http.request('GET', url.path)
response = http.getresponse()
image = RemoteImage(response)
- return self.store(image, user, response.getheader("Content-Type", "image/jpg"))
+ return self.store(image, user,
+ response.getheader("Content-Type", "image/jpg"))
def store(self, image, user, content_type):
key = self.create_unique_key()
@@ -58,14 +69,16 @@ def store(self, image, user, content_type):
"filename": filename}
thumbnail = self.create_thumbnail(image)
-
- metadata = self._metadata_bucket.new(key, data, content_type="application/json")
+
+ 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 = self._thumbs_bucket.new_binary(key, thumbnail,
+ content_type="image/jpeg")
thumb.store()
return key
@@ -76,7 +89,7 @@ def create_thumbnail(self, image):
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():
@@ -95,11 +108,8 @@ def find(self, image_id, thumb=False):
return None
def find_all(self, user):
- images = self.riak.search(settings.RIAK_METADATA_BUCKET, "user:%s" % user).map("""function(value) {
- var doc = Riak.mapValuesJson(value)[0];
- doc['id'] = value.key;
- return [doc];
- }""").run()
+ images = self.riak.search(settings.RIAK_METADATA_BUCKET,
+ "user:%s" % user).map(MAP_DOCID).run()
return images
def create_unique_key(self, length=6):
@@ -111,7 +121,7 @@ def create_unique_key(self, length=6):
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'
View
@@ -4,6 +4,7 @@
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'^t/(?P<image_id>[a-zA-Z0-9]{5,6})\.[a-z]{3}$', 'fetch',
+ {"thumb": True}),
url(r'^mine$', 'mine')
)
View
@@ -6,6 +6,7 @@
from images.services import ImageService, ImageError
from users.service import UserService
+
def upload(request):
if request.method == "POST":
upload = UploadForm(request.POST, request.FILES)
@@ -17,17 +18,21 @@ def upload(request):
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))
+ 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"])
+ 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))
@@ -37,14 +42,17 @@ def show(request, image_id):
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())
+ 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("/")
View
@@ -2,10 +2,14 @@
from django.core.management import execute_manager
import imp
try:
- imp.find_module('settings') # Assumed to be in the same directory.
+ 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.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
View
@@ -27,7 +27,7 @@
RIAK_BUCKET = 'django-riak-sessions'
SESSION_ENGINE = "django_riak"
APPEND_SLASH = False
-TIME_ZONE = 'Europe/London'
+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'
View
@@ -2,33 +2,53 @@
from django import forms
from django.forms.util import ErrorList
-
from users.service import UserService
+
class DivErrorList(ErrorList):
- def __unicode__(self):
- return self.as_divs()
- def as_divs(self):
- if not self: return u''
- return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
+ def __unicode__(self):
+ return self.as_divs()
+
+ def as_divs(self):
+ if not self:
+ return u''
+ errors = [u'<div class="error">%s</div>' % e for e in self]
+ return u'<div class="errorlist">%s</div>' % ''.join(errors)
+
class SignupForm(forms.Form):
- email = forms.EmailField(widget=forms.TextInput(attrs={'class':'text'}))
- username = forms.RegexField(regex=r'^\w+$', max_length=20, widget=forms.TextInput(attrs={'class':'text'}))
- password = forms.CharField(widget=forms.PasswordInput(render_value=False, attrs={'class':'text'}))
+ email = forms.EmailField(
+ widget=forms.TextInput(attrs={'class': 'text'}))
+
+ username = forms.RegexField(regex=r'^\w+$',
+ max_length=20,
+ widget=forms.TextInput(attrs={'class': 'text'})
+ )
+
+ password = forms.CharField(
+ widget=forms.PasswordInput(render_value=False,
+ attrs={'class': 'text'}))
def save(self):
user_data = self.cleaned_data
user_service = UserService()
return user_service.save(user_data)
+
class LoginForm(forms.Form):
- username = forms.RegexField(regex=r'^\w+$', max_length=20, widget=forms.TextInput(attrs={'class':'text'}))
- password = forms.CharField(widget=forms.PasswordInput(render_value=False, attrs={'class':'text'}))
+ username = forms.RegexField(regex=r'^\w+$',
+ max_length=20,
+ widget=forms.TextInput(attrs={'class': 'text'})
+ )
+
+ password = forms.CharField(
+ widget=forms.PasswordInput(render_value=False,
+ attrs={'class': 'text'}))
def clean(self):
user_service = UserService()
- user = user_service.login(self.cleaned_data['username'], self.cleaned_data['password'])
+ user = user_service.login(self.cleaned_data['username'],
+ self.cleaned_data['password'])
if user:
self.cleaned_data['user_id'] = user.get_key()
return self.cleaned_data
View
@@ -6,7 +6,9 @@
from django.utils.encoding import smart_str
from django.utils.crypto import constant_time_compare
-UNUSABLE_PASSWORD = '!' # This will never be a valid hash
+UNUSABLE_PASSWORD = '!' # This will never be a valid hash
+ALLOWEDCHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
+
def get_hexdigest(algorithm, salt, raw_password):
"""
@@ -18,7 +20,8 @@ def get_hexdigest(algorithm, salt, raw_password):
try:
import crypt
except ImportError:
- raise ValueError('"crypt" password algorithm not supported in this environment')
+ raise ValueError(
+ '"crypt" password algorithm not supported in this environment')
return crypt.crypt(raw_password, salt)
if algorithm == 'md5':
@@ -27,7 +30,8 @@ def get_hexdigest(algorithm, salt, raw_password):
return hashlib.sha1(salt + raw_password).hexdigest()
raise ValueError("Got unknown password algorithm type in password.")
-def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
+
+def get_random_string(length=12, allowed_chars=ALLOWEDCHARS):
"""
Returns a random string of length characters from the set of a-z, A-Z, 0-9
for use as a salt.
@@ -42,6 +46,7 @@ def get_random_string(length=12, allowed_chars='abcdefghijklmnopqrstuvwxyzABCDEF
pass
return ''.join([random.choice(allowed_chars) for i in range(length)])
+
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
@@ -53,8 +58,11 @@ def check_password(raw_password, enc_password):
algo, salt, hsh = parts
return constant_time_compare(hsh, get_hexdigest(algo, salt, raw_password))
+
def is_password_usable(encoded_password):
- return encoded_password is not None and encoded_password != UNUSABLE_PASSWORD
+ return (encoded_password is not None
+ and encoded_password != UNUSABLE_PASSWORD)
+
def make_password(algo, raw_password):
"""
@@ -66,10 +74,12 @@ def make_password(algo, raw_password):
hsh = get_hexdigest(algo, salt, raw_password)
return '%s$%s$%s' % (algo, salt, hsh)
+
class UserService:
def __init__(self):
self.users_bucket = settings.RIAK_USERS_BUCKET
- self.riak = RiakClient(host=settings.RIAK_HOST, port=settings.RIAK_PORT)
+ self.riak = RiakClient(host=settings.RIAK_HOST,
+ port=settings.RIAK_PORT)
def save(self, user_data):
key = self.generate_key()
@@ -89,7 +99,8 @@ def get(self, user_id):
def login(self, username, password):
try:
- user = self.riak.search(settings.RIAK_USERS_BUCKET, "username:%s" % username).run()
+ user = self.riak.search(settings.RIAK_USERS_BUCKET,
+ "username:%s" % username).run()
except ValueError:
user = None
Oops, something went wrong.

0 comments on commit a2df1f1

Please sign in to comment.