views.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # **************************************************************************
  4. # Copyright © 2016 jianglin
  5. # File Name: views.py
  6. # Author: jianglin
  7. # Email: xiyang0807@gmail.com
  8. # Created: 2016-12-21 21:56:41 (CST)
  9. # Last Update:星期三 2017-5-10 16:35:21 (CST)
  10. # By:
  11. # Description:
  12. # **************************************************************************
  13. from flask import (url_for, redirect, send_from_directory, current_app,
  14. request)
  15. from flask.views import MethodView
  16. from flask_login import login_required, current_user
  17. from flask_maple.form import form_validate
  18. from forums.api.forms import AvatarForm
  19. from werkzeug import secure_filename
  20. from time import time
  21. from random import randint
  22. from PIL import Image
  23. import os
  24. class AvatarView(MethodView):
  25. decorators = [login_required]
  26. @form_validate(
  27. AvatarForm, error=lambda: redirect(url_for('setting.setting')), f='')
  28. def post(self):
  29. form = AvatarForm()
  30. user = request.user
  31. file = request.files[form.avatar.name]
  32. filename = user.username + '-' + str(int(time())) + str(
  33. randint(1000, 9999))
  34. img = Image.open(file)
  35. size = 150, 150
  36. img.thumbnail(size, Image.ANTIALIAS)
  37. current_app.config.setdefault('AVATAR_FOLDER', os.path.join(
  38. current_app.static_folder, 'avatars'))
  39. avatar_path = current_app.config['AVATAR_FOLDER']
  40. avatar = os.path.join(avatar_path, filename + '.png')
  41. if not os.path.exists(avatar_path):
  42. os.makedirs(avatar_path)
  43. img.save(avatar)
  44. img.close()
  45. info = user.info
  46. if info.avatar:
  47. ef = os.path.join(avatar_path, info.avatar)
  48. if os.path.exists(ef):
  49. os.remove(ef)
  50. # file.save(os.path.join(app.static_folder, filename + '.png'))
  51. info.avatar = filename + '.png'
  52. info.save()
  53. return redirect(url_for('setting.setting'))
  54. class AvatarFileView(MethodView):
  55. def get(self, filename):
  56. current_app.config.setdefault('AVATAR_FOLDER', os.path.join(
  57. current_app.static_folder, 'avatars'))
  58. avatar_path = current_app.config['AVATAR_FOLDER']
  59. if not os.path.exists(os.path.join(avatar_path, filename)):
  60. filename = filename.split('-')[0]
  61. return redirect(url_for('avatar', text=filename))
  62. return send_from_directory(avatar_path, filename)