Commit 7bcf22e9 authored by Поляков Сергей Викторович's avatar Поляков Сергей Викторович
Browse files

- Added check that the link is a link.

- Added check for links already in the database, returns the previously generated link.
- Added "STORAGE_TYPE = redis" check when starting the server, all data from the db.yaml file will be loaded into the "Redis" database.
parent aca170ef
import pathlib
from flask import Flask, render_template, url_for, request, redirect
from lib.libs import Config
from lib.libs import Config, CheckUrl
from lib.yaml_lib import YamlManager
from lib.db_manager import DB_Manager
from lib import export_data_yml_to_redis as exp_data
current_dir = pathlib.Path.cwd()
conf = Config(pathlib.Path(current_dir, "pref.json"))
conf = Config(pathlib.Path(current_dir, "pref.json"))
yaml_manager = YamlManager(path=pathlib.Path("data", conf.name_yaml_bd))
if conf.storage == 'redis':
exp_data.export_data(yaml_manager, conf)
db = DB_Manager(config_class=conf, yaml_manager_class=yaml_manager)
app = Flask(__name__)
......@@ -29,14 +36,33 @@ def index():
all_links.update({key: db.get_by_key(key)})
if request.method == "POST":
new_link = add_link(value=request.form['full_link'],
method=request.form['generate_method'])
short_link_div = True
return render_template("index.html",
all_links=all_links,
short_link_div=short_link_div,
new_link=new_link,
domen_name=conf.domen_name)
value = request.form['full_link']
if db.value_exists(value):
key = db.value_exists(value)
primary_div = True
return render_template("index.html",
all_links=all_links,
primary_div=primary_div,
key=key,
domen_name=conf.domen_name)
else:
check = CheckUrl(value)
if check.is_link:
primary_div = True
new_link = add_link(value=request.form['full_link'], method=request.form['generate_method'])
return render_template("index.html",
all_links=all_links,
primary_div=primary_div,
key=new_link['key'],
domen_name=conf.domen_name)
else:
danger_div = True
return render_template("index.html",
value=value,
all_links=all_links,
danger_div=danger_div)
else:
short_link_div = False
return render_template("index.html",
......@@ -57,4 +83,3 @@ def redirecting(key):
@app.errorhandler(404)
def not_found(e):
return render_template('404.html')
......@@ -24,7 +24,7 @@ class DB_Manager:
else:
return False
def get_by_key(self, key):
def get_by_key(self, key:str) -> str:
"""Return value by key"""
if self._conf.storage == 'yaml':
return self._yaml_manager.get_by_key(key)
......@@ -58,6 +58,15 @@ class DB_Manager:
if not self.key_exist(link):
return link
def value_exists(self, value: str):
keys = self.get_keys()
if keys:
for k in keys:
if value == self.get_by_key(k):
return k
else:
return False
if __name__ == "__main__":
......@@ -69,4 +78,4 @@ if __name__ == "__main__":
conf = Config(Path("..", "pref.json"))
yaml_manager = YamlManager(path=Path("..", "data", conf.name_yaml_bd))
k = DB_Manager(conf, yaml_manager)
print(k.unique_link(generate_method='timestamp'))
print(k.value_exists('https://gitlab.mai.ru/PolyakovSV'))
\ No newline at end of file
......@@ -4,20 +4,23 @@ from lib.libs import Config
from pathlib import Path
conf = Config(Path("..", "pref.json"))
yaml_manager = YamlManager(path=Path("..", "data", conf.name_yaml_bd))
def export_data():
def export_data(yaml_manager, conf):
try:
for key in yaml_manager.get_keys():
value = yaml_manager.get_by_key(key)
print(f"Successfully added key: {key}, value: {value}")
with RedisManager(conf.redis_host, conf.redis_port, conf.redis_db) as f:
f.save(key, value)
except Exception as e:
print(f'Error: {e}')
print(f"Successfully added key: {key}, value: {value}")
except Exception:
return False
if __name__ == "__main__":
export_data()
conf = Config(Path("..", "pref.json"))
yaml_manager = YamlManager(path=Path("..", "data", conf.name_yaml_bd))
export_data(yaml_manager, conf)
......@@ -2,12 +2,15 @@ import datetime
import random
import uuid
import os
import re
import requests
import json
class Config:
"""Read json and return objects"""
def __init__(self, path):
"""path - path to pref.json"""
self._path = path
......@@ -40,7 +43,6 @@ class Config:
self.domen_name = domen_name
class LinkGenerator:
"""Generating link and returns a new in new_link variable
generate_method = "timestamp" or "uuid4" (by default) return six characters
......@@ -76,3 +78,47 @@ class LinkGenerator:
def _uuid4(self):
"""Returns first six characters"""
return str(uuid.uuid4())[:6]
class CheckUrl:
"""Return True if link exist"""
def __init__(self, url: str):
self._url = url
if self._parse_protocol(self._url):
self.is_link = self._check_url(self._url)
else:
if self._parse_www(self._url):
self._url = str('http://' + self._url)
self.is_link = self._check_url(self._url)
else:
self._url = str('http://www.' + self._url)
self.is_link = self._check_url(self._url)
def _parse_protocol(self, link: str) -> bool:
""" return True if https or http """
pattern = r'(https|http)'
res = re.match(pattern, link)
if res:
return True
else:
return False
def _parse_www(self, link: str) -> bool:
""" return True if www """
pattern = r'(www)'
res = re.match(pattern, link)
if res:
return True
else:
return False
def _check_url(self, url: str) -> bool:
try:
response = requests.head(url)
if response.status_code == 200:
return True
else:
return False
except:
return False
......@@ -18,7 +18,7 @@ class YamlManager:
for i in dictionary_data:
t.append(i['short_link'])
return t
except:
except Exception:
return False
def get_by_key(self, key):
......
{
"storage": "yaml",
"storage": "redis",
"name_yaml_bd": "db.yaml",
"redis_host" : "localhost",
"redis_port" : 6379,
......
......@@ -48,19 +48,34 @@ Main
<div class="link_generete">
{% if short_link_div %}
<div class="row">
{% if primary_div %}
<div class="row">
<div class="col">
</div>
<div class="col-10">
<div class="alert alert-success" role="alert">
Ваша коротакая ссылка <a href="{{ domen_name}}/{{key}}" target="_blank" class="alert-link">{{ domen_name}}/{{key}}</a>
</div>
</div>
<div class="col">
</div>
</div>
{% endif %}
{% if danger_div %}
<div class="row">
<div class="col">
</div>
<div class="col-10">
<div class="alert alert-success" role="alert">
Ваша коротакая ссылка <a href="{{ domen_name}}/{{new_link['key']}}" target="_blank" class="alert-link">{{ domen_name}}/{{new_link['key']}}</a>
<div class="alert alert-danger" role="alert">
Ошибка, не существующая ссылка <a href="{{value}}" target="_blank" class="alert-link">{{value}}</a>
</div>
</div>
<div class="col">
</div>
</div>
{% endif %}
{% endif %}
</div>
</div>
</div>
......@@ -91,7 +106,7 @@ Main
{% for k,v in all_links.items() %}
<tr>
<th scope="row">{{ loop.index0 + 1}}</th>
<td><a href="/{{k}}">{{ k }}</a></td>
<td><a href="/{{k}}" target="_blank">{{ k }}</a></td>
<td>{{ v }}</td>
</tr>
{% endfor %}
......
Markdown is supported
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