Commit 403bd37d authored by AntonKras's avatar AntonKras
Browse files

Добавлена README, добавлен запуск из консоли, исправления

parent 9a247b88
from flask import Flask, render_template, redirect, request, abort, flash
import re, os, random, string
import yaml
import yaml, sys
from werkzeug.urls import url_fix
from urllib.parse import urlparse, urlunparse, quote
app = Flask(__name__)
app.secret_key = os.urandom(24)
file = sys.argv[1]
@app.route('/', methods=['GET', 'POST'])
def main():
return render_template('index.html')
yaml_dict = extract_data_from_yml(file)
return render_template('index.html', yaml_dict=yaml_dict)
@app.route('/add', methods=['GET', 'POST'])
def add():
"""
функция добавления соответствия
:return redirect:
"""
url = request.args.get("url1")
yaml_dict = extract_data_from_yml(file)
if check_if_input_is_url(url) is None:
flash('URL введен некорректно')
flash('URL введен некорректно!')
return redirect('http://127.0.0.1:5000/')
elif url in yaml_dict.values():
flash('Соответствие с данным URL уже существует!')
return redirect('http://127.0.0.1:5000/')
else:
short_url = generate_short_url()
data = {short_url: url}
with open('static/urls.yml', 'a+', encoding='utf8') as f:
with open(file, 'a+', encoding='utf8') as f:
yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
f.close()
return redirect('http://127.0.0.1:5000/')
......@@ -31,9 +41,9 @@ def add():
@app.route('/<path:path>')
def redirect_somewhere(path):
yml_dict = extract_data_from_yml('static/urls.yml')
yml_dict = extract_data_from_yml(file)
if path in yml_dict:
return redirect(yml_dict[path])
return redirect(normalize(yml_dict[path]))
else:
return abort(404)
......@@ -44,37 +54,59 @@ def extract_data_from_yml(urls) -> dict:
:param urls:
:return dict:
"""
final_dict = {}
# r = redis.Redis('localhost')
final_dict = {} # словарь с данными из файла .yml
with open(urls, 'r') as stream:
try:
final_dict = yaml.safe_load(stream)
except yaml.YAMLError as exc:
final_dict = yaml.safe_load(stream) # загрузка данных в словарь
except yaml.YAMLError as exc: # обработка исключения
print(exc)
return final_dict
# r.hmset("pythonDict", final_dict)
# r.hgetall("pythonDict")
return final_dict # возвращения словаря
def generate_short_url() -> str:
rand_str = lambda n: ''.join([random.choice(string.ascii_lowercase) for i in range(n)])
"""
функция генерирования короткой ссылки
:return str:
"""
rand_str = lambda n: ''.join(
[random.choice(string.ascii_lowercase) for i in range(n)]) # составление короткой ссылки
return rand_str(5)
def check_if_input_is_url(url) -> None or not None:
"""
проверка является ли входной параметр ссылкой
:param url:
:return:
"""
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// или https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # домен
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...иди ip
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...или ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
answer = re.match(regex, url)
return answer
# def myquote(url):
# parts = urlparse(url)
# return urlunparse(parts._replace(path=quote(parts.path)))
def normalize(url: str) -> str:
"""
нормализация ссылки
:param url:
:return:
"""
if 'http' not in url:
url = 'http://' + url
return url
if __name__ == '__main__':
app.debug(True)
app.run()
......@@ -3,3 +3,6 @@ ram24: rambler.ru
ah712: yandex.ru
kzgcz: https://studfiles.net/preview/6716220/
vktlm: https://www.oslogic.ru/knowledge/598/shpargalka-po-osnovnym-komandam-postgresql/
mwimu: https://radiojazzfm.ru/
ahfsm: https://ru.wikipedia.org/wiki/%D0%9F%D0%BE%D1%82%D0%B5%D1%80%D1%8F%D0%BD%D0%BD%D0%BE%D0%B5_%D0%BF%D0%BE%D0%BA%D0%BE%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5
ulido: https://pythonbasics.org/flask-tutorial-routes/
......@@ -19,5 +19,10 @@
{% endif %}
{% endwith %}
</form>
{% for key in yaml_dict %}
{{ key + ':' + yaml_dict[key]}}<br/>
{% endfor %}
</body>
</html>
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment