From fe5596cd64c6ad74bb5b190f07a4340c738fe878 Mon Sep 17 00:00:00 2001 From: Nathan Cannon Date: Mon, 5 Oct 2015 23:19:11 +0100 Subject: [PATCH] Added rate limiting on api update requests. --- example-config.py | 2 +- static/quiz_item.coffee | 2 +- static/quiz_item.js | 2 +- wanikaniburned.py | 24 +++++++++++++++--------- 4 files changed, 18 insertions(+), 12 deletions(-) diff --git a/example-config.py b/example-config.py index 70f86aa..aff8ddc 100644 --- a/example-config.py +++ b/example-config.py @@ -3,4 +3,4 @@ SQLALCHEMY_DATABASE_URI = 'sqlite:///wanikani.db' SECRET_KEY = "putabettersecretkeyhere" DEBUG = False -PORT = 5000 \ No newline at end of file +PORT = 5000 diff --git a/static/quiz_item.coffee b/static/quiz_item.coffee index 1d4f27a..ead896e 100644 --- a/static/quiz_item.coffee +++ b/static/quiz_item.coffee @@ -67,7 +67,7 @@ $("#get-help").click (e) -> $("#api-refresh").click (e) -> e.preventDefault(); - $.post("{{ url_for('refresh_api') }}"); + $.post("/refresh"); refreshQuestion() $ -> diff --git a/static/quiz_item.js b/static/quiz_item.js index 877f96c..1722f13 100644 --- a/static/quiz_item.js +++ b/static/quiz_item.js @@ -90,7 +90,7 @@ $("#api-refresh").click(function(e) { e.preventDefault(); - $.post("{{ url_for('refresh_api') }}"); + $.post("/refresh"); return refreshQuestion(); }); diff --git a/wanikaniburned.py b/wanikaniburned.py index 1b67091..13ebb10 100644 --- a/wanikaniburned.py +++ b/wanikaniburned.py @@ -6,7 +6,7 @@ from flask.ext.wtf import Form import requests from wtforms import StringField from wtforms.validators import DataRequired -from datetime import datetime +from datetime import datetime, timedelta app = Flask(__name__) app.config.from_pyfile('config.py') @@ -93,12 +93,15 @@ class User(db.Model): self.vocabulary = json.dumps(items) def update_all(self): - self.parse_radicals_and_userdata() - self.parse_kanji() - self.parse_vocabulary() - self.last_updated = datetime.utcnow() - db.session.add(self) - db.session.commit() + if (datetime.now() - self.last_updated) > timedelta(hours=1): + self.parse_radicals_and_userdata() + self.parse_kanji() + self.parse_vocabulary() + self.last_updated = datetime.utcnow() + db.session.add(self) + db.session.commit() + else: + raise ValueError('Cannot refresh now, try again later.') @login_manager.user_loader @@ -173,8 +176,11 @@ def get_items(): @app.route('/refresh', methods=['POST']) def refresh_api(): - current_user.update_all() - return "202" + try: + current_user.update_all() + return "Refresh Successful", 202 + except ValueError as err: + return str(err), 500 @app.route('/logout')