-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
72 lines (58 loc) · 2.06 KB
/
models.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
import pickle
class Url(object):
@classmethod
def shorten(cls, full_url):
"""Shortens fulll url."""
# Create an instance of Url class
instance = cls()
instance.full_url = full_url
instance.short_url = instance.__create_short_url()
Url.__save_url_mapping(instance)
return instance
@classmethod
def get_by_short_url(cls, short_url):
"""Retunrns Url instance, correspoding to short_url."""
url_mapping = Url.__load_url_mapping()
return url_mapping.get(short_url)
def __create_short_url(self):
"""Creates short url, saves it and returns it."""
last_short_url = Url.__load_last_short_url()
short_url = self.__increment_string(last_short_url)
Url.__save_last_short_url(short_url)
return short_url
def __increment_string(self, string):
"""Increments string, that is:
a -> b
z -> aa
empty string -> a
"""
if string == '':
return 'a'
last_char = string[-1]
if last_char != 'z':
return string[:-1] + chr(ord(last_char) + 1)
return self.__increment_string(string[:-1]) + 'a'
@staticmethod
def __load_last_short_url():
"""Returns last generated short url."""
try:
return pickle.load(open("last_short.p", "rb"))
except IOError:
return ''
@staticmethod
def __save_last_short_url(url):
"""Saves last generated short url."""
pickle.dump(url, open("last_short.p", "wb"))
@staticmethod
def __load_url_mapping():
"""Returns short_url to Url instance mapping."""
try:
return pickle.load(open("short_to_url.p", "rb"))
except IOError:
return {}
@staticmethod
def __save_url_mapping(instance):
"""Saves short_url to Url instance mapping."""
short_to_url = Url.__load_url_mapping()
short_to_url[instance.short_url] = instance
pickle.dump(short_to_url, open("short_to_url.p", "wb"))