photolib/photoapp/utils.py

87 lines
2.3 KiB
Python

import os
import cherrypy
from photoapp.types import PhotoSet, PhotoStatus
import hashlib
from random import choice
import string
def copysha(fpin, fpout):
sha = hashlib.sha256()
while True:
b = fpin.read(1024 * 256)
if not b:
break
fpout.write(b)
sha.update(b)
return sha.hexdigest()
def shasum(fpin):
sha = hashlib.sha256()
while True:
b = fpin.read(4096)
if not b:
break
sha.update(b)
return sha.hexdigest()
def get_extension(fname):
parts = os.path.basename(fname).split(".")
if len(parts) == 1:
return None
return parts[-1].lower()
def auth():
"""
Return the currently authorized username (per request) or None
"""
return cherrypy.session.get('authed', None)
def require_auth(func):
"""
Decorator: raise 403 unless session is authed
"""
def wrapped(*args, **kwargs):
if not auth():
raise cherrypy.HTTPError(403, "Authentication required")
return func(*args, **kwargs)
return wrapped
def photoset_auth_filter(query):
"""
Sqlalchemy helper: filter the given PhotoSet query to items that match the authorized user's PhotoStatus access
level. Currently, authed users can access ALL photos, and unauthed users can access only PhotoStatus.public
status items.
"""
return query.filter(PhotoSet.status == PhotoStatus.public) if not auth() else query
def slugify(words):
return ''.join(letter for letter in '-'.join(words.lower().split())
if ('a' <= letter <= 'z') or ('0' <= letter <= '9') or letter == '-')
def cherryparam(v, type_=str):
"""
Cherrypy handles duplicate or list field names in post/get/body parameters by setting the parameter value to
a list of strings. However, if there is just one entry the parameter value is a string. Third, if the
field isn't provided the value is None. This function always returns a list of values.
"""
v = v or []
if type(v) == type_:
v = [v] # one entry
return v
def number_format(value):
return format(int(value), ',d')
def genpw(length=16):
return ''.join([choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(0, length)])