1
1
from flask import Flask , request , jsonify , redirect , render_template
2
+ from flask_limiter import Limiter
3
+ from flask_limiter .util import get_remote_address
2
4
import hashlib
3
5
import time
4
6
from sqlitedict import SqliteDict
5
7
from config import CONFIGS
6
8
7
9
app = Flask (__name__ )
8
10
11
+ limiter = Limiter (
12
+ app ,
13
+ key_func = get_remote_address ,
14
+ default_limits = ["100 per hour" ]
15
+ )
16
+
9
17
database = SqliteDict ("./%s" % CONFIGS ["DATABASE_NAME" ], autocommit = True )
10
18
11
19
'''
12
20
Root route, entry point for the shortener application.
13
21
'''
14
22
15
23
16
- @app .route ('/' , methods = ['GET' , 'POST' ])
17
- def index ():
24
+ @app .route ('/' , methods = ['GET' ])
25
+ @limiter .exempt
26
+ def get_index ():
18
27
if request .method == 'GET' :
19
28
# Use template engines/custom templates to send a form & handle form submit.
20
29
# return jsonify(error=False, message="OK!"), 200
21
30
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' :
23
39
# Someone used unorthodox method to shorten their URLs.
24
40
long_url = request .form .get ('url' )
25
41
if long_url != None and len (long_url ) >= 20 and is_valid_url (long_url ):
@@ -38,7 +54,8 @@ def index():
38
54
return jsonify (error = True , message = "Not OK!" ), 404
39
55
40
56
41
- @app .route ("/<id>" , methods = ['GET' , 'POST' ])
57
+ @app .route ("/<id>" , methods = ['GET' ])
58
+ @limiter .exempt
42
59
def navigate (id ):
43
60
if id != None and len (id ) == CONFIGS ['ID_LENGTH' ]:
44
61
if id in database :
@@ -63,6 +80,7 @@ def generate_id(url):
63
80
timestamp = md5 (url )
64
81
return timestamp [:CONFIGS ['ID_LENGTH' ]]
65
82
83
+
66
84
def url_exists (url ) -> bool :
67
85
url_id = generate_id (url )
68
86
if url_id in database :
0 commit comments