0% found this document useful (0 votes)
10 views

Menu Py

The document describes a Python Flask application that connects to multiple MySQL databases and allows different levels of access based on user credentials. It loads configuration files for database connections and menus. Blueprints are used to separate authentication, request handling, and menu display functionality. The application checks user credentials against the database and stores the user's access level in the session to determine which pages they can view.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Menu Py

The document describes a Python Flask application that connects to multiple MySQL databases and allows different levels of access based on user credentials. It loads configuration files for database connections and menus. Blueprints are used to separate authentication, request handling, and menu display functionality. The application checks user credentials against the database and stores the user's access level in the session to determine which pages they can view.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

CREATE USER 'director'@'127.0.0.

1' IDENTIFIED BY 'dir';

GRANT ALL ON `твоя_бд`.* TO `director`@`127.0.0.1`;

GRANT SELECT ON warehouse.user TO 'fict'@'127.0.0.1'

menu.py
import json
import mysql.connector
from flask import Flask, render_template, request, redirect, url_for, Blueprint, session

with open('data_files/dbconfig_director.json', 'r') as f:


dbconfig_director = json.load(f)
with open('data_files/menu.json', 'r') as f:
menu = json.load(f)
with open('data_files/dbconfig_fict.json', 'r') as f:
dbconfig_fict = json.load(f)
with open('data_files/secret_key.json', 'r') as f:
app_config = json.load(f)
Считываем из файла секретный ключ

app = Flask(__name__)
app.config['dbconfig_director'] = dbconfig_director
Передаем в словарь параметры подключения к базе данных
app.config['dbconfig_fict'] = dbconfig_fict
app.secret_key = app_config['secret_key']

from auth.auth import auth_blueprint


Импортируем блюпринт
app.register_blueprint(auth_blueprint, url_prefix = '/auth')
Регистрируем блюпринт авторизации

from requests.requests import requests_blueprint


app.register_blueprint(requests_blueprint, url_prefix = '/requests')

@app.route('/menu/', methods=['GET','POST'])
def main_menu():
if 'user_group' not in session:
session['user_group'] = 'fict'
route_mapping = {'1' : url_for('auth_blueprint.auth'),
'2' : url_for('requests_blueprint.requests')}
point = request.args.get('point')
if point is None:
return render_template('menu.html', menu = menu)
elif point in route_mapping:
return redirect(route_mapping[point])
Передаем управление одному из блюпринт
else:
return "Good bye"
app.run(debug = True)

request.py
import json
import mysql.connector
from DBCM import UseDatabase
from flask import Flask, render_template, request, redirect, url_for, Blueprint, current_app, session

with open('requests/data_files/access.json', 'r') as f:


access = json.load(f)

requests_blueprint = Blueprint('requests_blueprint', __name__, template_folder = 'templates',


static_folder = 'static')
Создаем экземпляр блюпринта вместо экземпляра фласк

@requests_blueprint.route('/', methods = ['POST', 'GET'])


Создаем декоратор функции для блюпринта
def requests():
print(session['user_group'])
if (session['user_group'] in access['groups']):
if 'send' in request.form and request.form['send']=='Send':
year_input = request.form.get('year')
if year_input:
with UseDatabase(current_app.config['dbconfig_director']) as cursor:
Выполняется выражение, выполняется метод энтер, выполняется блок инструкций,
выполняется метод экзит
employees = request1(cursor, year_input)
return render_template('request1.html', Year = year_input, employees = employees)
else:
return render_template('entry.html')
else:
return render_template('entry.html')
else:
return render_template('error.html')

def request1(cursor, year_input):


SQL = f"Select * From Zagotovki.workpiece Where YEAR(dolqu) = {year_input} "
cursor.execute(SQL)
result = cursor.fetchall()
res = []
schema = [ 'id_w', 'weight', 'dolqu', 'material', 'quantity', 'price' ]
for blank in result:
res.append(dict(zip(schema,blank)))
return res
auth.py
from flask import Flask, render_template,request,redirect, url_for, Blueprint, session, current_app
from DBCM import UseDatabase

auth_blueprint = Blueprint('auth_blueprint', __name__, template_folder = 'templates')

@auth_blueprint.route('/', methods = ['POST', 'GET'])


def auth():
if 'send' in request.form and request.form['send'] == 'Send':
login = request.form.get('login')
password = request.form.get('password')
print(login)
print(password)
if login and password:
with UseDatabase(current_app.config['dbconfig_fict']) as cursor:
Подключение к бд
if check(cursor, login, password):
SQL = f"""Select role From user Where login = '{login}' AND
password = '{password}'"""
cursor.execute(SQL)
result = cursor.fetchall()
result_string = str(result)
session['user_group'] = result_string[3:len(result_string) - 4]
Приведение результата сессии к нормальному виду
print(session['user_group'])
return redirect('/menu')
else:
return render_template('auth.html')
else:
return render_template('auth.html')
else:
return render_template('auth.html')

def check(cursor, login, password):


SQL = f"""Select count(*) From user Where login = '{login}' AND password = '{password}' """
cursor.execute(SQL)
result = cursor.fetchall()
res = result[0][0]
if (res == 0):
return False
return True

DBCM.py
import mysql.connector
import json

class UseDatabase:

def __init__(self, config: dict):


self.configuration = config
Выполняет инициализацию. Метод должен принимать входной словарь с параметрами
подключения. Параметры подключения должны быть сохранены в диспетчере контента.
def __enter__(self):
self.conn = mysql.connector.connect(**self.configuration)
self.cursor = self.conn.cursor()
return self.cursor
Выполняет натройки. Должен настроить объект, которым в нашем случае является курсор.
Именно курсор позволит отправлять запросы базе данных и получать из базы данных результаты
запроса. Оператор ** позволяет взять словарь с парами ключ значение и распаковать его в
именованные аргументы, как того требуют функция конннект. Этот метод использует параметры,
хранящиеся в self.configuration для подключения к бд. Затем создается курсор, который и
возвращает в качестве результата.
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.commit()
self.cursor.close()
self.conn.close()
Выполняет завершение операции. Выполняет завершающие действия по закрытию курсора и
разрыву соединения с бд.

dbconfig_director.json

dbconfig_fict.json

menu.json

secret_key.json
Каждый видит содержимое куки, но не может его менять, именно для этого и нужен секретный
ключ. Каждый последующий запрос к серверу этого приложения подтверждает подлинность куки
с помощью такого же секретного ключа. Если фласк не удается это сделать, тогда его контент
отклоняется, а браузер получает новые куки сессии. Такой тип сессии называется клиентским.
Отличается от обычного тем, что данные можно изменить только с помощью секретного ключа.
access.json

You might also like