-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.py
93 lines (60 loc) · 2.74 KB
/
model.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
from DB import *
from flask import json, redirect
from UrlGenerator import encode_url
import time
import requests
class model:
def is_safe(self, key, url):
URL = 'https://sb-ssl.google.com/safebrowsing/api/lookup?client=Safe&key={key}&appver=1.5.2&pver=3.1&url={url}'
response = requests.get(URL.format(key=key, url=url))
#print response.text
return response.text != 'malware'
def get_url_stats(self, short_url):
db = DB()
parts = short_url.split("/",3)
sql = '''SELECT clicks, short_url FROM links WHERE short_url=%s'''
query = db.query(sql, (parts[3], ))
link = query.fetchone()
if link is not None:
db.close()
return self.format_result(link['clicks'], 1, "Clicks on link "+short_url)
return self.format_result(None, 0, "Error"), 404
def make_short_url(self, url):
key = 'AIzaSyBwCHhPcVAdwZJH-hlTU4WM_sHe8-_SGYU'
if(self.is_safe(key, url) == True):
db = DB()
sql = '''SELECT id, short_url FROM links WHERE long_url=%s'''
query = db.query(sql, (url, ))
link = query.fetchone()
if link is not None:
db.close()
return self.format_result("http://goo.rs/"+link['short_url'], 1, "Links already exists")
else:
sql = '''SELECT MAX(id) as id FROM links'''
query = db.query(sql)
id = query.fetchone()
if id is not None:
short_url = encode_url(id['id'])
else:
short_url = encode_url(1)
sql = '''INSERT INTO links(id, long_url, short_url, clicks , u_id, created) VALUES (NULL, %s, %s, %s ,%s, %s )'''
db.query(sql, (url, short_url, 0, 2, time.strftime('%Y-%m-%d %H:%M:%S') ))
return self.format_result("http://goo.rs/"+short_url, 1, 'Url created')
return self.format_result({}, 0, "This url contains malware and can not be shortened.")
def format_result(self, result, status, message):
response = {'response': result, 'status': status, 'message': message}
return json.jsonify(response)
def redirect(self, url):
db = DB()
sql = '''SELECT id, long_url FROM links WHERE short_url=%s'''
query = db.query(sql, (url,))
link = query.fetchone()
if link is not None :
sql = '''UPDATE links SET clicks=clicks+1 WHERE id=%s'''
db.query(sql, (link['id'], ))
db.close()
key = 'AIzaSyBwCHhPcVAdwZJH-hlTU4WM_sHe8-_SGYU'
if(self.is_safe(key, link['long_url']) == True):
return (link['long_url'])
return False
return False