forked from francium/microurl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
microurl.py
206 lines (157 loc) · 4.31 KB
/
microurl.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import os
import random
import string
import sys
import time
from flask import abort, Flask, g, redirect, render_template, request, url_for,\
send_from_directory
from validators import domain as domaincheck
from validators import ipv4 as ipcheck
from validators import url as urlcheck
import database
import database_cleaner
import random_micro
#FLASK#########################################################################
app = Flask(__name__) # Instantiate a flask app.
db = database.DB_Interface()
@app.route('/')
def route_index():
'''
Main index page handler.
'''
return render_template('index.html')
@app.route('/about')
def route_about():
'''
About page handler.
'''
return render_template('about.html')
@app.route('/top')
def route_top():
'''
All registered micros page handler.
'''
return render_template('top.html', registry=read_top())
@app.route('/recent')
def route_recent():
'''
All registered micros page handler.
'''
return render_template('recent.html', registry=read_recent())
@app.route('/generate_micro', methods=['POST'])
def route_generate_micro():
'''
Generate micro POST request handler.
'''
data = parse_form_data(request.form)
micro = generate_micro()
# Store the micro and URL in the database.
register_micro(micro, data['url'], data['public'])
return micro
@app.route('/<micro>')
def route_micro(micro):
'''
Micro to real URL redirection handler.
'''
try:
temp = lookup_micro(micro)
if urlcheck(temp):
return redirect(temp)
elif domaincheck(temp):
return redirect("http://" + temp)
elif ipcheck(temp.split(':')[0]) and urlcheck('http://' + temp):
# checks for plain ip or an ip with something after it
return redirect("http://" + temp)
else:
abort(404)
except Exception as e:
# If micro is not registered, handle the exception from trying to look
# it up and raise a 404 HTTP error.
sys.stderr.write(str(e))
abort(404)
@app.errorhandler(404)
def route_404(error):
'''
Generate a 404 page.
'''
return 'invalid url'
@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico')
#BUSINESS LOGIC################################################################
def parse_form_data(form_data):
'''
Get form_data as a dict.
'''
try:
if form_data['public'] == 'on':
public = True
except KeyError:
public = False
url = form_data['url']
return {'url': url, 'public': public}
def generate_micro():
'''
Generates a random MICRO_LEN length ASCII code.
'''
return random_micro.random(3)
def lookup_micro(micro):
'''
Returns micro's associated url.
'''
try:
data = read_data(micro)
increment_hit(micro)
return data
except KeyError as e:
raise e
def register_micro(micro, url, public):
'''
Stores a micro and URL pair in the database.
'''
DAY_SECS = 24 * 60 * 60
with db:
tnow = int(time.time())
rc = db.insert(micro, url, tnow, tnow + DAY_SECS, public)
def read_top():
'''
Read all data from DB and return as dict.
'''
with db:
data = db.get_top()
if not(data):
return {'': 'nothing here'}
else:
return {d[1] : d[2] for d in data}
def read_recent():
'''
Read all data from DB and return as dict.
'''
with db:
data = db.get_recent()
if not(data):
return {'': 'nothing here'}
else:
return {d[1] : d[2] for d in data}
def read_data(query):
'''
Search for and return a query in the DB otherwise raise Exception.
'''
with db:
data = db.query(query)
if not(data):
raise KeyError('{} not found in database'.format(query))
else:
return data[2]
def increment_hit(query):
with db:
db.increment_hit(query)
def remove_expired():
'''
Clear expired links from databased.
'''
print('Clearing expired links.')
with db:
db.clear_expired()
database_cleaner.start(db, remove_expired)