Skip to content

Commit 1ee9421

Browse files
committed
Adds rate limit to the routes, separated routes for rate limit implementation.
1 parent 2f3806e commit 1ee9421

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

main.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,41 @@
11
from flask import Flask, request, jsonify, redirect, render_template
2+
from flask_limiter import Limiter
3+
from flask_limiter.util import get_remote_address
24
import hashlib
35
import time
46
from sqlitedict import SqliteDict
57
from config import CONFIGS
68

79
app = Flask(__name__)
810

11+
limiter = Limiter(
12+
app,
13+
key_func=get_remote_address,
14+
default_limits=["100 per hour"]
15+
)
16+
917
database = SqliteDict("./%s" % CONFIGS["DATABASE_NAME"], autocommit=True)
1018

1119
'''
1220
Root route, entry point for the shortener application.
1321
'''
1422

1523

16-
@app.route('/', methods=['GET', 'POST'])
17-
def index():
24+
@app.route('/', methods=['GET'])
25+
@limiter.exempt
26+
def get_index():
1827
if request.method == 'GET':
1928
# Use template engines/custom templates to send a form & handle form submit.
2029
# return jsonify(error=False, message="OK!"), 200
2130
return render_template('index.html', title=CONFIGS['SITE_INFO']['title'], description=CONFIGS['SITE_INFO']['description'], deploy_url=CONFIGS['DOMAIN'], year=CONFIGS['SITE_INFO']['year']), 200
22-
elif request.method == 'POST':
31+
else:
32+
return jsonify(error=True, message="Not OK!"), 404
33+
34+
35+
@app.route('/', methods=['POST'])
36+
@limiter.limit("1/second")
37+
def post_method():
38+
if request.method == 'POST':
2339
# Someone used unorthodox method to shorten their URLs.
2440
long_url = request.form.get('url')
2541
if long_url != None and len(long_url) >= 20 and is_valid_url(long_url):
@@ -38,7 +54,8 @@ def index():
3854
return jsonify(error=True, message="Not OK!"), 404
3955

4056

41-
@app.route("/<id>", methods=['GET', 'POST'])
57+
@app.route("/<id>", methods=['GET'])
58+
@limiter.exempt
4259
def navigate(id):
4360
if id != None and len(id) == CONFIGS['ID_LENGTH']:
4461
if id in database:
@@ -63,6 +80,7 @@ def generate_id(url):
6380
timestamp = md5(url)
6481
return timestamp[:CONFIGS['ID_LENGTH']]
6582

83+
6684
def url_exists(url) -> bool:
6785
url_id = generate_id(url)
6886
if url_id in database:

requirements.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
flask
2-
sqlitedict
2+
sqlitedict
3+
Flask-Limiter

0 commit comments

Comments
 (0)