Skip to content

Instantly share code, notes, and snippets.

@UndergroundLabs
Created October 21, 2015 21:56
Show Gist options
  • Save UndergroundLabs/c2eab21f8941e3c4acb9 to your computer and use it in GitHub Desktop.
Save UndergroundLabs/c2eab21f8941e3c4acb9 to your computer and use it in GitHub Desktop.
from flask import Blueprint, render_template, abort, jsonify, request
from flask.ext.login import login_required, current_user
from sqlalchemy.orm.exc import NoResultFound
from app import app, db
from app.models import Vote, Selfie
import datetime
vote_blueprint = Blueprint('vote', __name__, template_folder='templates')
def add_vote(user_id, selfie_id):
'''
Adds users vote to the database
'''
new_vote = Vote(user_id=user_id, selfie_id=selfie_id)
db.session.add(new_vote)
db.session.commit()
def rate_limit(user_id):
'''
Checks to see if a user is posting too quickly.
'''
vote = Vote.query.filter_by(user_id=current_user.id) \
.order_by(Vote.created_at.desc()) \
.first()
if vote:
future = vote.created_at + datetime.timedelta(seconds=app.config['VOTE_RATE_LIMIT'])
now = datetime.datetime.utcnow()
if future > now:
return True
return False
def has_user_voted(user_id, selfie_id):
'''
Checks whether the user has already voted on a given selfie.
Returns True on success, or False otherwise
'''
vote = Vote.query.filter_by(user_id=current_user.id, selfie_id=selfie_id).first()
if vote:
return True
return False
@vote_blueprint.route('/vote/<int:selfie_id>', methods=['GET'])
@login_required
def submit_vote(selfie_id):
#selfie_id = request.form['selfie_id']
# Get the selfie from the database
try:
selfie = Selfie.query.filter_by(id=selfie_id).one()
except NoResultFound, e:
return abort(404)
# Is the user voting too quickly?
if rate_limit(user_id=current_user.id):
return jsonify(error='Slow down, you\'re going too fast')
# Has the user already voted on this item?
if has_user_voted(user_id=current_user.id, selfie_id=selfie_id):
return jsonify(error='You have already voted on this selfie')
# Submit the users vote
add_vote(user_id=current_user.id, selfie_id=selfie_id)
return jsonify(success='Your vote was submitted')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment