Added rate limiting on api update requests.

This commit is contained in:
neviyn 2015-10-05 23:19:11 +01:00
parent a78bd4257f
commit fe5596cd64
4 changed files with 18 additions and 12 deletions

View File

@ -67,7 +67,7 @@ $("#get-help").click (e) ->
$("#api-refresh").click (e) -> $("#api-refresh").click (e) ->
e.preventDefault(); e.preventDefault();
$.post("{{ url_for('refresh_api') }}"); $.post("/refresh");
refreshQuestion() refreshQuestion()
$ -> $ ->

View File

@ -90,7 +90,7 @@
$("#api-refresh").click(function(e) { $("#api-refresh").click(function(e) {
e.preventDefault(); e.preventDefault();
$.post("{{ url_for('refresh_api') }}"); $.post("/refresh");
return refreshQuestion(); return refreshQuestion();
}); });

View File

@ -6,7 +6,7 @@ from flask.ext.wtf import Form
import requests import requests
from wtforms import StringField from wtforms import StringField
from wtforms.validators import DataRequired from wtforms.validators import DataRequired
from datetime import datetime from datetime import datetime, timedelta
app = Flask(__name__) app = Flask(__name__)
app.config.from_pyfile('config.py') app.config.from_pyfile('config.py')
@ -93,12 +93,15 @@ class User(db.Model):
self.vocabulary = json.dumps(items) self.vocabulary = json.dumps(items)
def update_all(self): def update_all(self):
self.parse_radicals_and_userdata() if (datetime.now() - self.last_updated) > timedelta(hours=1):
self.parse_kanji() self.parse_radicals_and_userdata()
self.parse_vocabulary() self.parse_kanji()
self.last_updated = datetime.utcnow() self.parse_vocabulary()
db.session.add(self) self.last_updated = datetime.utcnow()
db.session.commit() db.session.add(self)
db.session.commit()
else:
raise ValueError('Cannot refresh now, try again later.')
@login_manager.user_loader @login_manager.user_loader
@ -173,8 +176,11 @@ def get_items():
@app.route('/refresh', methods=['POST']) @app.route('/refresh', methods=['POST'])
def refresh_api(): def refresh_api():
current_user.update_all() try:
return "202" current_user.update_all()
return "Refresh Successful", 202
except ValueError as err:
return str(err), 500
@app.route('/logout') @app.route('/logout')