@@ -36,16 +36,6 @@ def gen_short() -> Iterator[str]:
36
36
length += 1
37
37
38
38
39
- def shorten (n : int ) -> str :
40
- """
41
- Get Nth short URL made from SDIGITS, where 0 is the first.
42
- """
43
- iter_short = gen_short ()
44
- for _ in range (n + 1 ):
45
- short = next (iter_short )
46
- return short
47
-
48
-
49
39
def gen_free_short (redirects : dict ) -> Iterator [str ]:
50
40
"""
51
41
Generate next available short URL.
@@ -55,25 +45,32 @@ def gen_free_short(redirects: dict) -> Iterator[str]:
55
45
yield short
56
46
57
47
58
- def new_urls (urls : list [str ], redirects : dict , targets : dict ) -> None :
48
+ def shorten (urls : list [str ], redirects : dict , targets : dict ) -> list [tuple [str ,str ]]:
49
+ """return (short, long) pairs, updating short.htaccess as needed""'
59
50
iter_short = gen_free_short(redirects)
51
+ pairs = []
60
52
with open('short.htaccess', 'a') as fp:
61
- for url in urls :
62
- assert 'fpy.li' not in url , f"{ url } is a fpy.li URL"
63
- if url in targets :
64
- continue
65
- short = next (iter_short )
66
- redirects [short ] = url
67
- targets [url ] = short
68
- fp .write (f"RedirectTemp /{ short } { url } \n " )
53
+ for long in urls:
54
+ assert 'fpy.li' not in long, f"{long} is a fpy.li URL"
55
+ if long in targets:
56
+ short = targets[long]
57
+ else:
58
+ short = next(iter_short)
59
+ redirects[short] = url
60
+ targets[url] = short
61
+ fp.write(f"RedirectTemp /{short} {url}\n ")
62
+ pairs.append((short, long))
63
+
64
+ return pairs
69
65
70
66
71
67
def main():
72
68
from random import randrange
73
69
urls = [f'https://example.com/{randrange(100000)}.html' for n in range(7)]
74
70
75
71
redirects, targets = load_redirects()
76
- new_urls (urls , redirects , targets )
72
+ for short, long in shorten(urls, redirects, targets):
73
+ print(f'fpy.li/{short}\t {long }')
77
74
78
75
79
76
if __name__ == '__main__' :
0 commit comments