Commit 9a247b88 authored by AntonKras's avatar AntonKras
Browse files

Добавлена функция "добавления соответствия {small_url:long_url}"

parent a0cca0a3
from flask import Flask, render_template, redirect, make_response
from flask import Flask, render_template, redirect, request, abort, flash
import re, os, random, string
import yaml
from werkzeug.urls import url_fix
from urllib.parse import urlparse, urlunparse, quote
app = Flask(__name__)
app.secret_key = os.urandom(24)
@app.route('/', methods=['GET'])
@app.route('/', methods=['GET', 'POST'])
def main():
return render_template('index.html')
@app.route('/', defaults={'path': ''})
@app.route('/add', methods=['GET', 'POST'])
def add():
url = request.args.get("url1")
if check_if_input_is_url(url) is None:
flash('URL введен некорректно')
return redirect('')
short_url = generate_short_url()
data = {short_url: url}
with open('static/urls.yml', 'a+', encoding='utf8') as f:
yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
return redirect('')
def redirect_somewhere(path):
yml_dict = extract_data_from_yml('static/urls.yml')
if path in yml_dict:
return redirect("https://www." + yml_dict[path])
return redirect(yml_dict[path])
return make_response(404)
return abort(404)
def extract_data_from_yml(urls) -> dict:
......@@ -26,17 +45,36 @@ def extract_data_from_yml(urls) -> dict:
:return dict:
final_dict = {}
with open(urls, 'r') as f:
content ='\n')
with open(urls, 'r') as stream:
final_dict = yaml.safe_load(stream)
except yaml.YAMLError as exc:
return final_dict
content = content[:-1]
for elem in content:
final_dict[elem.split(':')[0]] = elem.split(':')[1]
return final_dict
def generate_short_url() -> 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:
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+)?' # 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)))
if __name__ == '__main__':
......@@ -5,11 +5,19 @@
Введите ссылку в адресной строке
{#<p><b>Введите длинную ссылку:</b><br>#}
{#<form action="/add">#}
{# <input type="text" size="40">#}
{# <button>ff</button>#}
<p><b>Введите длинную ссылку:</b><br>
<form action="/add">
<input type="text" size="40" name="url1">
<button>Создать новое соответствие</button>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul class=flashes>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
{% endif %}
{% endwith %}
\ 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