Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sqlite3
- from contextlib import closing
- from flask import Flask, g
- from flask_sqlalchemy import SQLAlchemy
- from flask_login import LoginManager, UserMixin
- # from app.models import db
- from database import db
- application = Flask(__name__)
- application.config.from_object('config')
- application.debug = True
- db = SQLAlchemy(application)
- login_manager = LoginManager()
- login_manager.init_app(application)
- login_manager.login_view = "login"
- def to_int(id):
- # turns to an int
- class CRUDMixin(object):
- """Mixin that adds convenience methods for CRUD (create, read, update, delete)
- operations.
- """
- @classmethod
- def create(cls, **kwargs):
- """Create a new record and save it the database."""
- instance = cls(**kwargs)
- return instance.save()
- def update(self, commit=True, **kwargs):
- """Update specific fields of a record."""
- for attr, value in kwargs.iteritems():
- setattr(self, attr, value)
- return commit and self.save() or self
- def save(self, commit=True):
- """Save the record."""
- # with application.app_context():
- db.session.add(self)
- if commit:
- db.session.commit()
- return self
- def delete(self, commit=True):
- """Remove the record from the database."""
- # with application.app_context():
- db.session.delete(self)
- return commit and db.session.commit()
- class Model(CRUDMixin, db.Model):
- """Base model class that includes CRUD convenience methods."""
- __abstract__ = True
- def __init__(self, **kwargs):
- db.Model.__init__(self, **kwargs)
- # From Mike Bayer's "Building the app" talk
- # https://speakerdeck.com/zzzeek/building-the-app
- class SurrogatePK(object):
- """A mixin that adds a surrogate integer 'primary key' column named
- ``id`` to any declarative-mapped class.
- """
- __table_args__ = {'extend_existing': True}
- id = db.Column(db.Integer, primary_key=True)
- @classmethod
- def get_by_id(cls, id):
- _id = to_int(id)
- if _id is not None:
- return cls.query.get(_id)
- return None
- class Website(Model, SurrogatePK):
- __tablename__ = 'websites'
- name = db.Column(db.String(100), unique=True)
- url = db.Column(db.String(250), unique=True)
- user_id = db.Column(db.Integer, db.ForeignKey('users.email'))
- def __repr__(self):
- return "{}: {}".format(self.name, self.url)
- class User(Model, UserMixin):
- """
- :param str email: email address of user
- :param str password: encrypted password for the user
- """
- __tablename__ = 'users'
- email = db.Column(db.String, primary_key=True)
- password = db.Column(db.String)
- authenticated = db.Column(db.Boolean, default=False)
- approved = db.Column(db.Boolean, default=False)
- admin = db.Column(db.Boolean, default=False)
- websites = db.relationship('Website', backref='websites', lazy='dynamic')
- def get_id(self):
- return self.email
- from flask_sqlalchemy import SQLAlchemy
- db = SQLAlchemy()
- def login():
- form = LoginForm(request.form)
- if request.method == 'POST':
- if form.validate_on_submit():
- email = form.email.data
- password = form.password.data
- user = User.query.filter_by(email=email, password=password).first()
- if user:
- login_user(user)
- current_user.authenticated = True
- print('logging in')
- print(current_user.authenticated)
- flash('Logged in successfully.')
- return redirect(url_for('admin'))
- handle_login_form(form)
- return render_template('login.html', form=form)
- @application.route('/admin/', methods=['GET', 'POST'])
- @login_required
- def admin():
- print(current_user)
- print(current_user.is_authenticated)
- print(current_user.approved)
- print(current_user.admin)
- print(current_user.email)
- if current_user.is_authenticated and not current_user.approved:
- return redirect(url_for('awaiting_approval'))
- logging in
- True
- <app.User object at 0x7fb52fcc7390>
- True
- None
- None
- email@fake.com
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement