暂无描述

models.py 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- encoding: utf-8 -*-
  2. """
  3. License: MIT
  4. Copyright (c) 2019 - present AppSeed.us
  5. """
  6. from flask_login import UserMixin
  7. from sqlalchemy import Binary, Column, Integer, String
  8. from app import db, login_manager
  9. from app.base.util import hash_pass
  10. class User(db.Model, UserMixin):
  11. __tablename__ = 'User'
  12. id = Column(Integer, primary_key=True)
  13. username = Column(String, unique=True)
  14. email = Column(String, unique=True)
  15. password = Column(Binary)
  16. def __init__(self, **kwargs):
  17. for property, value in kwargs.items():
  18. # depending on whether value is an iterable or not, we must
  19. # unpack it's value (when **kwargs is request.form, some values
  20. # will be a 1-element list)
  21. if hasattr(value, '__iter__') and not isinstance(value, str):
  22. # the ,= unpack of a singleton fails PEP8 (travis flake8 test)
  23. value = value[0]
  24. if property == 'password':
  25. value = hash_pass( value ) # we need bytes here (not plain str)
  26. setattr(self, property, value)
  27. def __repr__(self):
  28. return str(self.username)
  29. @login_manager.user_loader
  30. def user_loader(id):
  31. return User.query.filter_by(id=id).first()
  32. @login_manager.request_loader
  33. def request_loader(request):
  34. username = request.form.get('username')
  35. user = User.query.filter_by(username=username).first()
  36. return user if user else None