Answer the question
In order to leave comments, you need to log in
What is the link shortener algorithm?
Interested in the algorithm. How a shortened link is generated. I'm going to implement in python.
Answer the question
In order to leave comments, you need to log in
Em. generate any short sequence.
save it as a key - the link
does not necessarily generate a short link in the usual way. you can just use randomness.
And you can generate a hash from the URL and cut and remember where necessary.
I am learning python and it was also interesting to write a shortcut, somewhere I found an implementation in php. rewritten for python 3.x.
#!/usr/bin/python
__author__ = 'ZeLib0ba -> http://surin.ru'
import random
from os import path
def urlsh(long_url): # возвращает короткую ссылку вида http://surin.ru/sh/eGbWp
domain_name='http://surin.ru/'
phph_file_folder='./sh/'
if not path.exists('.htaccess'):
ht_f=open('.htaccess','w')# если нет создаем файл .htaccess
ht_f.write('RewriteEngine On\nRewriteBase %s\n' % phph_file_folder[1:-1])# записываем в него первые две строчки для переадресации
else:
ht_f=open('.htaccess','a')
link=''.join(random.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',5)) # генерируем случайную последовательность из 5 символов для нашей короткой ссылки
data=phph_file_folder + link + '.php'
php_file=open(data,'w')
php_file.write('<?php header(\'Location: %s\') ?>\n' % long_url)
php_file.close()
ht_f.write('RewriteRule ^%s %s%s' % (link,phph_file_folder[2:],link+'.php\n'))
ht_f.close()
return domain_name + phph_file_folder[2:] + link
a=urlsh('http://yandex.ru')
print(a)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question