@@ -36,16 +36,6 @@ def gen_short() -> Iterator[str]:
3636 length += 1
3737
3838
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-
4939def gen_free_short (redirects : dict ) -> Iterator [str ]:
5040 """
5141 Generate next available short URL.
@@ -55,25 +45,32 @@ def gen_free_short(redirects: dict) -> Iterator[str]:
5545 yield short
5646
5747
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""'
5950 iter_short = gen_free_short(redirects)
51+ pairs = []
6052 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
6965
7066
7167def main():
7268 from random import randrange
7369 urls = [f'https://example.com/{randrange(100000)}.html' for n in range(7)]
7470
7571 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 }')
7774
7875
7976if __name__ == '__main__' :
0 commit comments