Advertisement
Guest User

Untitled

a guest
May 5th, 2016
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.09 KB | None | 0 0
  1. import sqlite3
  2. from contextlib import closing
  3.  
  4. from flask import Flask, g
  5. from flask_sqlalchemy import SQLAlchemy
  6. from flask_login import LoginManager, UserMixin
  7.  
  8. # from app.models import db
  9. from database import db
  10.  
  11. application = Flask(__name__)
  12. application.config.from_object('config')
  13. application.debug = True
  14.  
  15. db = SQLAlchemy(application)
  16.  
  17. login_manager = LoginManager()
  18. login_manager.init_app(application)
  19.  
  20. login_manager.login_view = "login"
  21.  
  22.  
  23.  
  24.  
  25. def to_int(id):
  26. # turns to an int
  27.  
  28.  
  29.  
  30. class CRUDMixin(object):
  31. """Mixin that adds convenience methods for CRUD (create, read, update, delete)
  32. operations.
  33. """
  34.  
  35. @classmethod
  36. def create(cls, **kwargs):
  37. """Create a new record and save it the database."""
  38. instance = cls(**kwargs)
  39. return instance.save()
  40.  
  41. def update(self, commit=True, **kwargs):
  42. """Update specific fields of a record."""
  43. for attr, value in kwargs.iteritems():
  44. setattr(self, attr, value)
  45. return commit and self.save() or self
  46.  
  47. def save(self, commit=True):
  48. """Save the record."""
  49. # with application.app_context():
  50. db.session.add(self)
  51. if commit:
  52. db.session.commit()
  53. return self
  54.  
  55. def delete(self, commit=True):
  56. """Remove the record from the database."""
  57. # with application.app_context():
  58. db.session.delete(self)
  59. return commit and db.session.commit()
  60.  
  61.  
  62. class Model(CRUDMixin, db.Model):
  63. """Base model class that includes CRUD convenience methods."""
  64. __abstract__ = True
  65.  
  66. def __init__(self, **kwargs):
  67. db.Model.__init__(self, **kwargs)
  68.  
  69.  
  70. # From Mike Bayer's "Building the app" talk
  71. # https://speakerdeck.com/zzzeek/building-the-app
  72. class SurrogatePK(object):
  73. """A mixin that adds a surrogate integer 'primary key' column named
  74. ``id`` to any declarative-mapped class.
  75. """
  76. __table_args__ = {'extend_existing': True}
  77.  
  78. id = db.Column(db.Integer, primary_key=True)
  79.  
  80. @classmethod
  81. def get_by_id(cls, id):
  82. _id = to_int(id)
  83. if _id is not None:
  84. return cls.query.get(_id)
  85. return None
  86.  
  87.  
  88. class Website(Model, SurrogatePK):
  89. __tablename__ = 'websites'
  90.  
  91. name = db.Column(db.String(100), unique=True)
  92. url = db.Column(db.String(250), unique=True)
  93. user_id = db.Column(db.Integer, db.ForeignKey('users.email'))
  94.  
  95. def __repr__(self):
  96. return "{}: {}".format(self.name, self.url)
  97.  
  98.  
  99. class User(Model, UserMixin):
  100. """
  101. :param str email: email address of user
  102. :param str password: encrypted password for the user
  103. """
  104. __tablename__ = 'users'
  105.  
  106. email = db.Column(db.String, primary_key=True)
  107. password = db.Column(db.String)
  108. authenticated = db.Column(db.Boolean, default=False)
  109. approved = db.Column(db.Boolean, default=False)
  110. admin = db.Column(db.Boolean, default=False)
  111. websites = db.relationship('Website', backref='websites', lazy='dynamic')
  112.  
  113. def get_id(self):
  114. return self.email
  115.  
  116. from flask_sqlalchemy import SQLAlchemy
  117.  
  118. db = SQLAlchemy()
  119.  
  120. def login():
  121. form = LoginForm(request.form)
  122. if request.method == 'POST':
  123. if form.validate_on_submit():
  124. email = form.email.data
  125. password = form.password.data
  126. user = User.query.filter_by(email=email, password=password).first()
  127. if user:
  128. login_user(user)
  129. current_user.authenticated = True
  130. print('logging in')
  131. print(current_user.authenticated)
  132. flash('Logged in successfully.')
  133. return redirect(url_for('admin'))
  134. handle_login_form(form)
  135. return render_template('login.html', form=form)
  136.  
  137. @application.route('/admin/', methods=['GET', 'POST'])
  138. @login_required
  139. def admin():
  140. print(current_user)
  141. print(current_user.is_authenticated)
  142. print(current_user.approved)
  143. print(current_user.admin)
  144. print(current_user.email)
  145. if current_user.is_authenticated and not current_user.approved:
  146. return redirect(url_for('awaiting_approval'))
  147.  
  148. logging in
  149. True
  150.  
  151. <app.User object at 0x7fb52fcc7390>
  152. True
  153. None
  154. None
  155. email@fake.com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement