Merge branch 'Requests' into Auth

This commit is contained in:
2024-11-14 15:16:05 +03:00
13 changed files with 108 additions and 55 deletions

View File

@@ -1,8 +1,7 @@
from flask import request, Blueprint, render_template
from flask import request, Blueprint, render_template, url_for
from os import path
from checker import check_auth
from .requests_model import sklad, materials_per_seller
from datetime import date
import json
with open(path.join(path.dirname(__file__), 'zapros_menu.json')) as f:
@@ -14,14 +13,14 @@ requests_bp = Blueprint('requests_bp', __name__, template_folder='templates')
@check_auth
def requests():
if request.method == 'GET':
return render_template('zapros_menu.html', options=requests_list)
return render_template('pages_menu.html', options=requests_list, header='Запросы')
@requests_bp.route('/sklad', methods=['GET', 'POST'])
@check_auth
def sklad_zapros():
if request.method == 'GET':
materials = ['Сталь', 'Алюминий', 'Медь', 'Пластик', 'Дерево']
return render_template('zagotovki.html', materials=materials, header='Количество заготовок на складе')
# materials = ['Сталь', 'Алюминий', 'Медь', 'Пластик', 'Дерево']
return render_template('zagotovki.html', header='Количество заготовок на складе')
else:
material = dict(request.form)
zagotovki = sklad(material)
@@ -30,37 +29,18 @@ def sklad_zapros():
return render_template('output.html', items=zagotovki.result, header=header)
else:
return render_template('error.html', error_message=zagotovki.error_message)
# Под вопросом
""" @requests_bp.route('/req2', methods=['GET', 'POST'])
@check_auth
def zagotovki_ship():
if request.method == 'GET':
zagotovki = get_goods()
if zagotovki.status:
return render_template('zagotovki.html', materials=zagotovki.result, header='Поставки заготовок')
else:
return render_template('error.html', error_message=zagotovki.error_message)
else:
material = dict(request.form)
zagotovki = route(material, 'zapros2.sql')
if zagotovki.status:
header = f'Поставки заготовок из материала \'{material['material']}\''
return render_template('output.html', items=zagotovki.result, object=header)
else:
return render_template('error.html', error_message=zagotovki.error_message) """
@requests_bp.route('/shipments', methods=['GET', 'POST'])
@check_auth
def sellers_ship():
if request.method == 'GET':
sellers = ['Alpha Supplies', 'Beta Materials', 'Gamma Parts', 'Delta Components', 'Epsilon Goods']
return render_template('sellers_ship.html', sellers=sellers)
# sellers = ['Alpha Supplies', 'Beta Materials', 'Gamma Parts', 'Delta Components', 'Epsilon Goods']
return render_template('sellers_ship.html')
else:
seller = dict(request.form)
zagotovki = materials_per_seller(seller)
if zagotovki.status:
header = f'Поставки от поставщика \"{seller["seller"]}\"'
return render_template('output.html', items=zagotovki.result, header=header)
return render_template('output.html', items=zagotovki.result, header=header, link=url_for('requests_bp.requests'))
else:
return render_template('error.html', error_message=zagotovki.error_message)

View File

@@ -0,0 +1,34 @@
import pymysql
from pymysql.err import *
class DBContextManager:
def __init__(self, db_config : dict):
self.db_config = db_config
self.connection = None
self.cursor = None
def __enter__(self):
try:
self.connection = pymysql.connect(
host=self.db_config['host'],
port=self.db_config['port'],
user=self.db_config['user'],
password=self.db_config['password'],
db=self.db_config['db']
)
self.cursor = self.connection.cursor()
return self.cursor
except (OperationalError, KeyError) as err:
print(err.args)
return None
def __exit__(self, exc_type, exc_val, exc_tb):
if self.connection and self.cursor:
if exc_type:
print(exc_type, '\n', exc_val)
self.connection.rollback()
else:
self.connection.commit()
self.cursor.close()
self.connection.close()
return True

View File

12
App/Requests/db/select.py Normal file
View File

@@ -0,0 +1,12 @@
from .DBconnect import DBContextManager
def select_list(db_config, sql) -> list:
with DBContextManager(db_config) as cursor:
if cursor is None:
raise ValueError("Cursor not created")
else:
cursor.execute(sql)
result = cursor.fetchall()
schema = [item[0] for item in cursor.description]
lst = [dict(zip(schema, row)) for row in result]
return lst

View File

@@ -0,0 +1,14 @@
import os
from string import Template
class SQLProvider:
def __init__(self, file_path):
self.scripts = {}
for file in os.listdir(file_path):
_sql = open(f'{file_path}/{file}').read()
self.scripts[file] = Template(_sql)
def get(self, name, params) -> dict:
if name not in self.scripts:
raise ValueError(f'SQL template {name} not found')
return self.scripts[name].substitute(**params)

View File

@@ -1,6 +1,6 @@
from dataclasses import dataclass
from Database.select import select_list
from Database.sql_provider import SQLProvider
from db.select import select_list
from db.sql_provider import SQLProvider
from flask import current_app
from os import path

View File

@@ -1,13 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ошибка</title>
<link href="/static/css/main.css" type="text/css" rel="stylesheet">
</head>
<body>
<h1>Произошла ошибка</h1>
<p>{{ error_message }}.</p>
<a href="{{ url_for('index') }}"><button>На главную страницу</button></a>
</body>
</html>

View File

@@ -1,8 +1,8 @@
<!DOCTYPE html>
<html lang="en">
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Все поставки поставщиком</title>
<title>Поставки поставщиком</title>
<link href="/static/css/main.css" type="text/css" rel="stylesheet">
</head>
<body>
@@ -10,14 +10,16 @@
<a href="{{ url_for('logout') }}"><button>Выход</button></a>
</div>
<!-- Input -->
<h1>Все поставки поставщиком</h1>
<h1>Поставки поставщиком</h1>
<div class="form">
<p>Выберите поставщика</p>
<form action="" method="post">
<select name="seller">
{% for item in sellers %}
<option value="{{ item }}">{{ item }}</option>
{% endfor %}
<option value="Alpha Supplies">Alpha Supplies</option>
<option value="Beta Materials">Beta Materials</option>
<option value="Gamma Parts">Gamma Parts</option>
<option value="Delta Components">Delta Components</option>
<option value="Epsilon Goods">Epsilon Goods</option>
</select>
<input type="submit" value="Отправить">
</form>

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en">
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>{{ header }}</title>
@@ -15,9 +15,11 @@
<form action="" method="post" style="display: inline-block;">
<p>Выберите материал<p></p>
<select name="material">
{% for item in materials %}
<option value="{{ item }}">{{ item }}</option>
{% endfor %}
<option value="Сталь">Сталь</option>
<option value="Алюминий">Алюминий</option>
<option value="Медь">Медь</option>
<option value="Пластик">Пластик</option>
<option value="Дерево">Дерево</option>
</select>
<input type="submit" value="Отправить">
</form>

View File

@@ -1,5 +1,5 @@
<!DOCTYPE html>
<html lang="en">
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Запросы</title>

View File

@@ -1,5 +1,5 @@
[
{"name": "Количество заготовок на складе", "url": "requests_bp.sklad_zapros"},
{"name": "Поставки поставщиком за год", "url": "requests_bp.sellers_ship"}
{"name": "Поставки поставщиками", "url": "requests_bp.sellers_ship"}
]

View File

@@ -31,6 +31,6 @@
<p>Информации не найдено</p>
{% endif %}
<div class="return">
<a href="{{ url_for('requests_bp.requests') }}"><button>Обратно в меню запросов</button></a>
<a href="{{ link }}"><button>Вернуться в меню выбора</button></a>
</div></body>
</html>

View File

@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ header }}</title>
<link href="/static/css/main.css" type="text/css" rel="stylesheet">
</head>
<body>
<div class="logout">
<a href="{{ url_for('logout') }}"><button>Выход</button></a>
</div>
<h1>Выберите один из предложенных вариантов</h1>
<nav class="menu">
{% for point in options %}
<a href="{{ url_for(point['url']) }}"><button>{{ point['name'] }}</button></a>
{% endfor %}
</nav>
<div class="return">
<a href="{{ url_for('index') }}"><button>Главное меню</button></a>
</div>
</body>
</html>