Advertisement
Guest User

Untitled

a guest
Dec 27th, 2016
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.10 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # python import
  3. import os
  4. import shutil
  5. from PIL import Image
  6. import random
  7. import re
  8. import mimetypes
  9. from io import StringIO
  10. # django import
  11. from django.db import models
  12. from django.db.models.signals import post_save
  13. from django.conf import settings
  14. from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
  15. from django.core.mail import send_mail
  16. from django.core.files import File
  17. from django.template.loader import render_to_string
  18. from django.utils import timezone
  19. from django.utils.crypto import get_random_string
  20. from django.core.files.uploadedfile import SimpleUploadedFile
  21.  
  22.  
  23. class UserManager(BaseUserManager):
  24. # 일반 유저 생성
  25.  
  26. def create_user(self, email, password=None):
  27. # 이메일이 없는 경우 에러 호출
  28. if not email:
  29. raise ValueError("이메일은 필수 항목입니다.")
  30.  
  31. user = self.model(
  32. email=self.normalize_email(email)
  33. )
  34. user.set_password(password)
  35. user.save()
  36.  
  37. return user
  38.  
  39. # 관리자 계정 생성
  40. def create_superuser(self, email, password=None):
  41. user = self.create_user(
  42. email,
  43. password=password
  44. )
  45. user.is_active = True
  46. user.is_admin = True
  47. user.save(using=self._db)
  48. return user
  49.  
  50.  
  51. def user_profile_location(instance, filename):
  52. return "users/%s/%s" % (instance, filename)
  53.  
  54.  
  55. class User(AbstractBaseUser):
  56. email = models.EmailField(max_length=255, unique=True)
  57. name = models.CharField(max_length=20, null=True, blank=True)
  58. phone = models.CharField(max_length=20, null=True, blank=True)
  59. image = models.ImageField(
  60. null=True,
  61. blank=True,
  62. upload_to=user_profile_location
  63. )
  64. is_active = models.BooleanField(default=False)
  65. is_admin = models.BooleanField(default=False)
  66.  
  67. objects = UserManager()
  68.  
  69. USERNAME_FIELD = 'email'
  70.  
  71. def __str__(self):
  72. return str(self.email)
  73.  
  74. def get_short_name(self):
  75. if self.name:
  76. return self.name
  77. return self.email.split('@')[0]
  78.  
  79. @property
  80. def is_staff(self):
  81. return self.is_admin
  82.  
  83. @property
  84. def get_user_profile_image(self):
  85. if self.image:
  86. return '/media/%s' % (self.image)
  87. return "/public/img/no_profile_1.png"
  88.  
  89. @property
  90. def get_user_micro_thumb(self):
  91. micro = Thumbnail.objects.filter(user=self, type='micro')
  92. if micro.exists():
  93. return '/media/%s' % (micro[0].image)
  94. return self.get_user_profile_image
  95.  
  96. @property
  97. def get_user_hd_thumb(self):
  98. hd = Thumbnail.objects.filter(user=self, type='hd')
  99. if hd.exists():
  100. return '/media/%s' % (hd[0].image)
  101. return self.get_user_profile_image
  102.  
  103. def has_perm(self, perm, obj=None):
  104. return True
  105.  
  106. def has_module_perms(self, app_label):
  107. return True
  108.  
  109.  
  110. def thumbnail_location(instance, filename):
  111. return "users/%s/thumb/%s" % (instance.user, filename)
  112.  
  113.  
  114. THUMB_CHOICES = (
  115. ("hd", "HD"),
  116. ("sd", "SD"),
  117. ("micro", "Micro"),
  118. )
  119.  
  120.  
  121. class Thumbnail(models.Model):
  122. user = models.ForeignKey(User)
  123. type = models.CharField(max_length=20, choices=THUMB_CHOICES, default='hd')
  124. height = models.CharField(max_length=20, null=True, blank=True)
  125. width = models.CharField(max_length=20, null=True, blank=True)
  126. image = models.ImageField(
  127. width_field="width",
  128. height_field="height",
  129. blank=True,
  130. null=True,
  131. upload_to=thumbnail_location)
  132.  
  133. def __str__(self):
  134. return str(self.image.path)
  135.  
  136.  
  137. def user_post_save_receiver(sender, instance, created, *args, **kwargs):
  138. if instance.image:
  139. hd, hd_created = Thumbnail.objects.get_or_create(user=instance, type='hd')
  140. sd, sd_created = Thumbnail.objects.get_or_create(user=instance, type='sd')
  141. micro, micro_created = Thumbnail.objects.get_or_create(user=instance, type='micro')
  142.  
  143. hd_max = (250, 250)
  144. sd_max = (100, 100)
  145. micro_max = (50, 50)
  146.  
  147. image_path = instance.image.path
  148. if hd_created:
  149. create_new_thumb(image_path, hd, hd_max[0], hd_max[1])
  150.  
  151. if sd_created:
  152. create_new_thumb(image_path, sd, sd_max[0], sd_max[1])
  153.  
  154. if micro_created:
  155. create_new_thumb(image_path, micro, micro_max[0], micro_max[1])
  156.  
  157.  
  158. post_save.connect(user_post_save_receiver, sender=User)
  159.  
  160.  
  161. def create_new_thumb(image_path, instance, max_length, max_width):
  162. filename = os.path.basename(image_path)
  163. thumb = Image.open(image_path)
  164. size = (max_length, max_width)
  165.  
  166. thumb.thumbnail(size, Image.ANTIALIAS)
  167. crop_img = Image.new('RGBA', size, (255, 255, 255, 0))
  168. crop_img.paste(
  169. thumb,
  170. ((size[0] - thumb.size[0]) // 2, (size[1] - thumb.size[1]) // 2))
  171.  
  172. dir_name = os.path.dirname(os.path.abspath(image_path))
  173. user_id = os.path.split(dir_name)[1]
  174.  
  175. temp_loc = "%s/users/%s/thumb/temp" % (settings.MEDIA_ROOT, user_id)
  176.  
  177. if not os.path.exists(temp_loc):
  178. os.makedirs(temp_loc)
  179. temp_file_path = os.path.join(temp_loc, filename)
  180.  
  181. if os.path.exists(temp_file_path):
  182. temp_path = os.path.join(temp_loc, "%s" % (random.random()))
  183. os.makedirs(temp_path)
  184. temp_file_path = os.path.join(temp_path, filename)
  185.  
  186. temp_image = open(temp_file_path, "wb")
  187. crop_img.save(temp_image, "JPEG")
  188.  
  189. thumb_data = open(temp_file_path, "rb")
  190. thumb_file = File(thumb_data)
  191. instance.image.save(filename, thumb_file)
  192. shutil.rmtree(temp_loc, ignore_errors=True)
  193.  
  194. return True
  195.  
  196.  
  197. class EmailConfirmed(models.Model):
  198. user = models.OneToOneField(User)
  199. activation_key = models.CharField(max_length=140, null=True, blank=True)
  200. confirmed = models.BooleanField(default=False)
  201. key_expire = models.DateTimeField(default=timezone.now)
  202.  
  203. def __str__(self):
  204. return str(self.confirmed)
  205.  
  206. def activate_user_email(self):
  207. activation_url = "localhost:8000/password/reset/%s" % (
  208. self.activations_key)
  209.  
  210. context = {
  211. "activation_key": self.activation_key,
  212. "user": self.user,
  213. "activation_url": activation_url
  214. }
  215.  
  216. html_message = render_to_string(
  217. "templates/users/activation_user_message.html", context)
  218. subject = ''
  219. message = ''
  220. self.email_user(subject, message, settings.EMAIL_MAIN, html_message)
  221.  
  222. def send_mail(self, subject, message, from_email=None, html_message=None):
  223. send_mail(subject, message, from_email, [
  224. self.user.email], fail_silently=False, html_message=html_message)
  225.  
  226.  
  227. class PasswordReset(models.Model):
  228. user = models.ForeignKey(User)
  229. activation_key = models.CharField(max_length=140, null=True, blank=True)
  230. confirmed = models.BooleanField(default=False)
  231. key_expire = models.DateTimeField(default=timezone.now)
  232.  
  233. def __str__(self):
  234. return str(self.confirmed)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement