Skip to content

Instantly share code, notes, and snippets.

@dmrqx
Created September 6, 2017 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmrqx/a3b9932bba607fab84ad27b6103acdb1 to your computer and use it in GitHub Desktop.
Save dmrqx/a3b9932bba607fab84ad27b6103acdb1 to your computer and use it in GitHub Desktop.
Understanding Python's @Property decorator usage
import os
import hashlib
import time
import urllib.request
import numpy as np
class Photo(object):
sources = None
def __init__(self, source_type):
self.source_type = source_type
self.uploads_folder = 'uploads'
self.min_width = self.min_height = 200
@property
def filename(self):
return self.__filename
@filename.setter
def filename(self, ext='jpg'):
filehash = hashlib.sha1()
filehash.update(str(time.time()).encode('utf-8'))
filename = filehash.hexdigest()[:18] + '.' + ext
if not os.path.exists(self.uploads_folder):
os.makedirs(self.uploads_folder)
self.__filename = os.path.join(self.uploads_folder,
filename)
@classmethod
def set_source(self, source_type):
if self.sources is None:
self.sources = {}
for source_class in self.__subclasses__():
source = source_class()
self.sources[source.source_type] = source
return self.sources[source_type]
class FacebookPhoto(Photo):
def __init__(self):
super(FacebookPhoto, self).__init__('facebook')
def save_file(self, url):
with urllib.request.urlopen(url) as url:
f = np.asarray(bytearray(url.read()), dtype='uint8')
f = cv2.imdecode(f, cv2.IMREAD_COLOR)
cv2.imwrite(self.filename, f)
class LocalPhoto(Photo):
def __init__(self):
super(LocalPhoto, self).__init__('local')
def save_file(self, formdata):
ext = formdata.mimetype.split('/')[1]
formdata.save(self.filename(ext))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment