Last active
December 29, 2017 13:27
-
-
Save iamOgunyinka/7e92b25df2d94eb80fc5a742e1213ebc to your computer and use it in GitHub Desktop.
A temporary fix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from views import init_blueprints | |
app = init_blueprints() | |
if __name__ == '__main__': | |
app.run(debug=True, port=80) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask_sqlalchemy import SQLAlchemy | |
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user | |
from werkzeug.security import generate_password_hash, check_password_hash | |
db = SQLAlchemy() | |
class User(db.Model, UserMixin): | |
__name__ = "User" | |
id = db.Column(db.Integer, primary_key=True, index=True) | |
full_name = db.Column(db.String(255)) | |
email = db.Column(db.String(255), unique=True) | |
password_hash = db.Column(db.String(255)) | |
is_confirmed = db.Column(db.Boolean, default=False) | |
post_counter = db.Column(db.BigInteger, default=0) | |
daily_post = db.Column(db.Integer, default=0) | |
user_balance = db.Column(db.BigInteger, default=0) | |
@property | |
def password(self): | |
raise AttributeError('Cannot get plain password') | |
@password.setter | |
def password(self, data): | |
self.password_hash = generate_password_hash(data) | |
@property | |
def confirmed(self): | |
return self.is_confirmed | |
def verify_password(self, passwd): | |
return check_password_hash(self.password_hash, passwd) | |
def __repr__(self): | |
return '<User -> fullname: {}, email: {}, confirmed: {}'.format(self.full_name, self.email, self.is_confirmed) | |
class General(db.Model): | |
__name__ = "General" | |
id = db.Column(db.Integer, primary_key=True) | |
post_type = db.Column(db.String(20)) | |
post_title = db.Column(db.String(50)) | |
posted_by = db.Column(db.String(50)) | |
location = db.Column(db.String(20)) | |
content = db.Column(db.Text) | |
#attach_image= db.Column(db.LargeBinary) | |
date_posted = db.Column(db.DateTime) | |
display_name = db.Column(db.String(255)) | |
post_viewer = db.Column(db.Integer, default=0) | |
class Politics(db.Model): | |
__name__ = "Politics" | |
id = db.Column(db.Integer, primary_key=True) | |
post_type = db.Column(db.String(20)) | |
post_title = db.Column(db.String(50)) | |
posted_by = db.Column(db.String(50)) | |
location = db.Column(db.String(20)) | |
#attach_image= db.Column(db.LargeBinary) | |
content = db.Column(db.Text) | |
date_posted = db.Column(db.DateTime) | |
display_name = db.Column(db.String(255)) | |
post_viewer = db.Column(db.Integer, default=0) | |
class Entertainment(db.Model): | |
__name__ = "Entertainment" | |
id = db.Column(db.Integer, primary_key=True) | |
post_type = db.Column(db.String(20)) | |
post_title = db.Column(db.String(50)) | |
posted_by = db.Column(db.String(50)) | |
location = db.Column(db.String(20)) | |
#attach_image= db.Column(db.LargeBinary) | |
content = db.Column(db.Text) | |
date_posted = db.Column(db.DateTime) | |
display_name = db.Column(db.String(255)) | |
post_viewer = db.Column(db.Integer, default=0) | |
class Sport(db.Model): | |
__name__ = 'Sport' | |
id = db.Column(db.Integer, primary_key=True) | |
post_type = db.Column(db.String(20)) | |
post_title = db.Column(db.String(50)) | |
posted_by = db.Column(db.String(50)) | |
location = db.Column(db.String(20)) | |
#attach_image= db.Column(db.LargeBinary) | |
content = db.Column(db.Text) | |
date_posted = db.Column(db.DateTime) | |
display_name = db.Column(db.String(255)) | |
post_viewer = db.Column(db.Integer, default=0) | |
class Technology(db.Model): | |
__name__ = 'Technology' | |
id = db.Column(db.Integer, primary_key=True) | |
post_type = db.Column(db.String(20)) | |
post_title = db.Column(db.String(50)) | |
posted_by = db.Column(db.String(50)) | |
location = db.Column(db.String(20)) | |
#attach_image= db.Column(db.LargeBinary) | |
content = db.Column(db.Text) | |
date_posted = db.Column(db.DateTime) | |
display_name = db.Column(db.String(255)) | |
post_viewer = db.Column(db.Integer, default=0) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import render_template, request, url_for, redirect, flash, jsonify, Blueprint, Flask | |
from models import User, Politics, Technology, General, Entertainment, Sport, db | |
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user | |
from sqlalchemy.exc import IntegrityError | |
from werkzeug.exceptions import BadRequest | |
from datetime import datetime | |
import os | |
#~ mail = Mail(app) | |
#~ s = URLSafeTimedSerializer('My_Biggest_Secret') | |
# ========================= I needed all these to make this view function self-contain ======================== | |
ERROR, SUCCESS = 0, 1 | |
auth = Blueprint('auth', __name__) | |
app = Flask(__name__) | |
login_manager = LoginManager() | |
def init_blueprints(): | |
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY') | |
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DB_URL') | |
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True | |
app.register_blueprint(auth, url_prefix='/auth') | |
db.init_app(app) | |
login_manager.init_app(app) | |
login_manager.login_view = 'app.login_handler' | |
return app | |
# before every 'auth' request, we need to make sure they're logged in and use confirmed accounts | |
@auth.before_request | |
def before_auth_request(): | |
if not current_user.is_authenticated: | |
return error_response('Not logged in') | |
@app.route('/login', methods=['POST']) | |
def login_handler(): | |
try: | |
data = request.get_json() | |
if data is None: | |
return error_response('Invalid request sent') | |
email = data.get('email', None) | |
password = data.get('password', None) | |
user = db.session.query(User).filter_by(email=email).first() | |
if user is None: | |
return error_response('Invalid login detail') | |
if not user.verify_password(password): | |
return error_response('Invalid username or password') | |
login_user(user, False) | |
return success_response('You\'re logged in') | |
except BadRequest as br: | |
print br | |
return error_response('Invalid login request received.') | |
@login_manager.user_loader | |
def load_user(user_id): | |
return User.query.get(int(user_id)) | |
@auth.route('/logout') | |
@login_required | |
def logout(): | |
logout_user() | |
return success_response('You have been logged out') | |
# Make it such that it returns the correct error response page, I only used JSON here. | |
def respond_back(status_code, message): | |
return jsonify( { 'status': status_code, 'detail': message } ) | |
def error_response(message): | |
return respond_back(ERROR, message) | |
def success_response(message): | |
return respond_back(SUCCESS, message) | |
# ===================== The end ========================================= | |
# to add a post, a user must be logged in. | |
@auth.route('/addpost', methods=['POST']) | |
@login_required | |
def addpost_handler(): | |
# by the time the view function reaches here, we are guaranteed to have a valid user in current_user, OK let's confirm | |
print current_user | |
posttype = request.form['posttype'] | |
post_title = request.form['posttitle'] | |
location = request.form['location'] | |
content = request.form['content'] | |
posted_by = current_user.full_name | |
within_post_limit = current_user.post_counter < 10 and current_user.daily_post < 10 and current_user.daily_post < 1000 | |
post = None | |
# all these branches have something similar, so we faction them out and do them at the end. | |
if all((posttype == 'politics', within_post_limit, )): | |
post = Politics(post_type=posttype,post_title=post_title, posted_by=posted_by, location=location, | |
content=content, date_posted=datetime.now()) | |
elif all((posttype == 'general', within_post_limit, )): | |
post = General(post_type=posttype,post_title=post_title, posted_by=posted_by, location=location, | |
content=content, date_posted=datetime.now()) | |
elif posttype == 'entertainment' and within_post_limit: | |
post = Entertainment(post_type=posttype,post_title=post_title, posted_by=posted_by, location=location, | |
content=content, date_posted=datetime.now()) | |
elif posttype == 'sport' and within_post_limit: | |
post = Sport(post_type=posttype,post_title=post_title, posted_by=posted_by, location=location, | |
content=content, date_posted=datetime.now()) | |
elif posttype == 'tech' and within_post_limit: | |
post = Technology(post_type=posttype,post_title=post_title, posted_by=posted_by, location=location, | |
content=content, date_posted=datetime.now()) | |
flash('Thank You Content Posted') | |
else: | |
return error_response('Post type is not selected or not available') | |
# if we got to this part of the code, then there was no error, now let's try commit those changes | |
current_user.post_counter += 1 | |
current_user.daily_post += 1 | |
current_user.user_balance += 100 | |
db.session.add(post) | |
db.session.add(current_user) | |
try: | |
db.session.commit() | |
return success_response('Posted by: ' + posted_by) | |
except IntegrityError as int_error: | |
print int_error # for us to see but not to the general public | |
return error_response('There was an error saving your post') | |
@app.before_first_request | |
def before_first_request(): | |
db.drop_all() | |
db.configure_mappers() | |
db.create_all() | |
new_user = User(full_name='Your name', email='iamHuman@email.com', password='idontknow', is_confirmed=True) | |
db.session.add(new_user) | |
db.session.commit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment