from flask import Flask, render_template, request, redirect, make_response, jsonify, send_file, Response
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.sql import func
from datetime import datetime, timedelta, date
import pandas as pd
from io import BytesIO
import json
import queue
import logging
from sqlalchemy import cast, Integer, or_
import os
app = Flask(name)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///table_data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class TableRow(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(10), nullable=False)
row_number = db.Column(db.String(10))
timestamp = db.Column(db.String(50))
number = db.Column(db.String(50))
serial = db.Column(db.String(50))
dl_number = db.Column(db.String(50))
worker_name = db.Column(db.String(100))
pack_time = db.Column(db.String(50))
last_graf = db.Column(db.String(50))
arma_type = db.Column(db.String(50))
class DLCounter(db.Model):
id = db.Column(db.Integer, primary_key=True)
date = db.Column(db.String(10), unique=True, nullable=False)
counter = db.Column(db.Integer, nullable=False)
@app.route('/get_unpacked_days', methods=['GET'])
def get_unpacked_days():
year = request.args.get('year')
month = request.args.get('month')
if not year or not month:
return jsonify({"status": "error", "message": "Необходимо указать год и месяц"}), 400
try:
year = int(year)
month = int(month)
except ValueError:
return jsonify({"status": "error", "message": "Год и месяц должны быть числами"}), 400
# Формируем формат даты для фильтрации
month_str = f"{month:02d}"
# Запрашиваем уникальные дни, где pack_time отсутствует и arma_type равен 'RPA'
unpacked_dates = TableRow.query.filter(
TableRow.date.like(f"{year}-{month_str}-%"),
TableRow.arma_type == 'RPA',
or_(TableRow.pack_time == None, TableRow.pack_time == '')
).with_entities(TableRow.date).distinct().all()
# Извлекаем дни из дат
unpacked_days = set()
for date_str, in unpacked_dates:
try:
day = int(date_str.split('-')[2])
unpacked_days.add(day)
except (IndexError, ValueError):
continue # Пропускаем некорректные форматы дат
return jsonify({'status': 'success', 'unpacked_days': list(unpacked_days)})
Assistant
@app.route('/stream')
def stream():
def event_stream():
while True:
try:
# Ожидаем новое сообщение с таймаутом 20 секунд
data = update_queue.get(timeout=20)
yield f'data: {data}\n\n'
except queue.Empty:
# Отправляем keep-alive комментарий, чтобы соединение не разорвалось
yield ': keep-alive\n\n'
return Response(event_stream(), mimetype='text/event-stream')
Удален маршрут /ping, так как он использовал ActiveUser
@app.route('/get_table_data')
def get_table_data():
date = request.args.get('date')
filter_arma = request.args.get('filter_arma') # Новый параметр фильтра
# Начинаем построение запроса
query = TableRow.query.filter_by(date=date)
# Если фильтр активирован, добавляем условие
if filter_arma == 'RPA':
query = query.filter_by(arma_type='RPA')
rows = query.all()
data = []
numbers = {}
serials = {}
dl_numbers = {} # Добавляем словарь для dl_numbers
for row in rows:
data.append({
'id': row.id, # Добавляем ID записи
'row_number': row.row_number,
'timestamp': row.timestamp,
'number': row.number,
'serial': row.serial,
'dl_number': row.dl_number,
'worker_name': row.worker_name,
'pack_time': row.pack_time,
'arma_type': row.arma_type,
'last_graf': row.last_graf
})
# Собираем информацию о дубликатах
if row.number:
clean_number = ''.join(filter(str.isdigit, row.number))
if clean_number in numbers:
numbers[clean_number].append(len(data) - 1) # Индекс строки
else:
numbers[clean_number] = [len(data) - 1]
if row.serial:
clean_serial = ''.join(filter(str.isdigit, row.serial))
if clean_serial in serials:
serials[clean_serial].append(len(data) - 1) # Индекс строки
else:
serials[clean_serial] = [len(data) - 1]
if row.dl_number:
clean_dl_number = ''.join(filter(str.isdigit, row.dl_number))
if clean_dl_number in dl_numbers:
dl_numbers[clean_dl_number].append(len(data) - 1)
else:
dl_numbers[clean_dl_number] = [len(data) - 1]
# Фильтруем только реальные дубликаты
duplicate_numbers = {k: v for k, v in numbers.items() if len(v) > 1}
duplicate_serials = {k: v for k, v in serials.items() if len(v) > 1}
duplicate_dl_numbers = {k: v for k, v in dl_numbers.items() if len(v) > 1}
return jsonify({
"data": data,
"duplicates": {
"numbers": duplicate_numbers,
"serials": duplicate_serials,
"dl_numbers": duplicate_dl_numbers # Добавляем dl_numbers
}
})
@app.route('/update_table', methods=['POST'])
def update_table():
data = request.json
print(data)
date = data['date']
worker_name = data['worker_name']
arma_type = data['arma_type']
# Получаем количество существующих записей для этой даты
row_count = TableRow.query.filter_by(date=date).count() + 1
# Создаём новую строку в таблице
if not data.get('number') and not data.get('serial'):
new_row = TableRow(
date=date,
row_number=str(row_count),
timestamp=data['timestamp'],
number='', # Пустое значение для номера
serial='', # Пустое значение для серийного номера
dl_number='', # Пустое значение для графы
worker_name=worker_name,
arma_type=arma_type,
)
elif not data.get('number'):
new_row = TableRow(
date=date,
row_number=str(row_count),
timestamp=data['timestamp'],
number='', # Пустое значение для номера
serial=data['serial'],
dl_number='', # Пустое значение для графы
worker_name=worker_name,
arma_type=arma_type,
)
else:
new_row = TableRow(
date=date,
row_number=str(row_count),
timestamp=data['timestamp'],
number=data['number'],
serial=data['serial'],
dl_number=data.get('dl_number', ''),
worker_name=worker_name,
arma_type=arma_type,
)
# Сохраняем запись в базе данных
db.session.add(new_row)
# Ранее здесь была логика обновления ActiveUser, удалим ее
db.session.commit()
# Отправляем сообщение в очередь для обновления клиентов
update_queue.put(json.dumps({"type": "update", "date": date}))
return jsonify({"status": "success"})
@app.route('/update_graf', methods=['POST'])
def update_graf():
try:
data = request.json
row_id = int(data.get('id'))
new_value = data.get('new_value')
date = data.get('date')
if not row_id or not date:
return jsonify({"status": "error", "message": "Missing 'id' or 'date' in request"}), 400
# Находим запись по id и дате
row = TableRow.query.filter_by(id=row_id, date=date).first()
if row:
row.dl_number = new_value
db.session.commit()
return jsonify({"status": "success"})
else:
return jsonify({"status": "error", "message": "Row not found"}), 404
except (ValueError, TypeError) as e:
return jsonify({"status": "error", "message": f"Invalid input: {str(e)}"}), 400
except Exception as e:
db.session.rollback()
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/update_arma_type', methods=['POST'])
def update_arma_type():
try:
data = request.json
date = data['date']
serial = data['serial']
arma_type = data['arma_type']
row = TableRow.query.filter_by(date=date, serial=serial).first()
if row:
row.arma_type = arma_type
db.session.commit()
return jsonify({"status": "success"})
else:
return jsonify({"status": "error", "message": "Row not found"})
except Exception as e:
return jsonify({"status": "error", "message": str(e)})
@app.route('/update_number', methods=['POST'])
def update_number():
try:
data = request.json
row_id = int(data['id']) # Используем 'id' вместо 'row_index'
new_value = data['new_value']
date = data['date']
# Находим запись по id и дате
row = TableRow.query.filter_by(id=row_id, date=date).first()
if row:
row.number = new_value
db.session.commit()
return jsonify({"status": "success"})
return jsonify({"status": "error", "message": "Row not found"})
except Exception as e:
db.session.rollback()
return jsonify({"status": "error", "message": str(e)})
@app.route('/pack_item', methods=['POST'])
def pack_item():
try:
data = request.json
row_id = data['id']
date = data['date']
rows = TableRow.query.filter_by(id=row_id, date=date).all()
if rows:
row = rows[0]
pack_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
row.pack_time = pack_time
db.session.commit()
# Отправляем сообщение в очередь для обновления клиентов
update_queue.put(json.dumps({"type": "update", "date": date}))
return jsonify({"status": "success", "pack_time": pack_time})
return jsonify({"status": "error", "message": "Строка не найдена"}), 404
except Exception as e:
print(f"Ошибка в pack_item: {str(e)}")
return jsonify({"status": "error", "message": str(e)}), 500
@app.route('/set_initial_dl', methods=['POST'])
def set_initial_dl():
try:
data = request.json
if not data:
return jsonify({"status": "error", "message": "No data received"})
date = data.get('date')
initial_number = data.get('initial_number')
if not date or not initial_number:
return jsonify({
"status": "error",
"message": "Missing required fields",
"received": {"date": date, "initial_number": initial_number}
})
try:
initial_number = int(initial_number)
except ValueError:
return jsonify({
"status": "error",
"message": "Initial number must be an integer"
})
print(f"Setting initial DL for date {date}: {initial_number}") # Отладочный вывод
dl_counter = DLCounter.query.filter_by(date=date).first()
if dl_counter:
dl_counter.counter = initial_number
print(f"Updated existing counter for {date}") # Отладочный вывод
else:
dl_counter = DLCounter(date=date, counter=initial_number)
db.session.add(dl_counter)
print(f"Created new counter for {date}") # Отладочный вывод
db.session.commit()
return jsonify({
"status": "success",
"message": f"DL counter set to {initial_number} for date {date}"
})
except Exception as e:
print(f"Error in set_initial_dl: {str(e)}") # Отладочный вывод
db.session.rollback()
return jsonify({
"status": "error",
"message": str(e)
})
@app.route('/generate_dl', methods=['POST'])
def generate_dl():
try:
data = request.json
row_id = data['id']
date = data['date']
# Получаем или создаем счетчик DL для данной даты
dl_counter = DLCounter.query.filter_by(date=date).first()
if not dl_counter:
return jsonify({"status": "error", "message": "DL counter не инициализирован"}), 400
# Генерируем новый DL номер
dl_number = f"DL{dl_counter.counter:06d}"
# Находим и обновляем нужную запись по id
row = TableRow.query.filter_by(id=row_id, date=date).first()
if row:
row.dl_number = dl_number
dl_counter.counter += 1 # Увеличиваем счетчик
db.session.commit()
return jsonify({"status": "success", "dl_number": dl_number, "id": row_id})
return jsonify({"status": "error", "message": "Строка не найдена"}), 404
except Exception as e:
return jsonify({"status": "error", "message": str(e)}), 500
def initialize_table_for_date(date):
# Проверяем, существуют ли уже записи для этой даты
existing = TableRow.query.filter_by(date=date).first()
if not existing:
# Создаем новую запись только в случае отсутствия данных
new_row = TableRow(
date=date,
row_number=str(1),
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
number='',
serial='',
dl_number='',
worker_name='',
arma_type='',
pack_time='',
last_graf=''
)
db.session.add(new_row)
db.session.commit()
@app.route('/update_serial_arma', methods=['POST'])
def update_serial_arma():
try:
data = request.json
date = data['date']
serial = data['serial']
arma_type = data['arma_type']
# Создаем новую запись в таблице
new_row = TableRow(
date=date,
serial=serial,
arma_type=arma_type,
timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S")
)
db.session.add(new_row)
db.session.commit()
return jsonify({"status": "success"})
except Exception as e:
db.session.rollback()
return jsonify({"status": "error", "message": str(e)}), 500
Удален маршрут /register_user, так как он использовал ActiveUser
Удален маршрут /get_active_users, так как он использовал ActiveUser
if not row_id:
return jsonify({'status': 'error', 'message': 'ID записи не предоставлен'}), 400
row = TableRow.query.get(row_id)
if not row:
return jsonify({'status': 'error', 'message': 'Запись не найдена'}), 404
db.session.delete(row)
db.session.commit()
# Отправляем сообщение в очередь для обновления клиентов
update_queue.put(json.dumps({"type": "delete", "date": row.date, "id": row.id}))
return jsonify({'status': 'success'})
except Exception as e:
db.session.rollback()
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/', methods=['GET', 'POST'])
def main():
if request.method == 'POST':
worker = request.form.get('worker')
name = request.form.get('name')
# Сохраняем информацию о входе
user = User.query.filter_by(username=name).first()
if not user:
user = User(username=name)
db.session.add(user)
login_history = LoginHistory(user=user)
db.session.add(login_history)
db.session.commit()
resp = make_response(redirect('/welcome'))
resp.set_cookie('worker', worker)
resp.set_cookie('name', name)
return resp
return render_template('main.html')
@app.route('/get_current_dl', methods=['GET'])
def get_current_dl():
date = request.args.get('date')
if not date:
return jsonify({"status": "error", "message": "Дата обязательна"}), 400
dl_counter = DLCounter.query.filter_by(date=date).first()
if dl_counter:
return jsonify({"status": "success", "current_dl": dl_counter.counter})
else:
return jsonify({"status": "error", "message": "Счетчик DL не инициализирован для этой даты"}), 404
@app.route('/welcome')
def welcome():
worker = request.cookies.get('worker')
name = request.cookies.get('name')
if not worker or not name:
return redirect('/')
return render_template('welcome.html', name=name, worker=worker, table=table)
Certainly! Let's perform a comprehensive review of your Flask application. I'll break down the analysis into several key sections: Architecture & Structure, Database Models, Routes & Functionality, Error Handling & Logging, Security Considerations, Performance Optimizations, and Code Quality & Best Practices. Finally, I'll provide Recommendations for Improvement.
1. Architecture & Structure
Strengths:
Modular Design: You've organized your application using Flask's blueprint system implicitly by keeping models, routes, and configurations within a single file. While this works for smaller applications, it can become unwieldy as the project grows.
Areas for Improvement:
File Organization: Consider breaking down the application into multiple modules/files:
models.py for database models.
routes.py or separate blueprints for different functionalities.
utils.py for utility functions.
config.py for configuration settings.
This enhances readability, maintainability, and scalability.
2. Database Models
Strengths:
Use of SQLAlchemy: Leveraging SQLAlchemy ORM for database interactions is a good choice for abstraction and ease of use.
Relationships Defined: The relationship between User and LoginHistory is appropriately defined.
Areas for Improvement:
Data Types:
Dates and Timestamps: Instead of using db.String for date and timestamp fields (e.g., in TableRow), utilize appropriate date/time types like db.Date or db.DateTime. This allows SQLAlchemy and the database to handle date-specific operations more effectively.
Performance Enhancements: Add indexes to frequently queried fields such as date, arma_type, and possibly serial or number if they are frequently used in WHERE clauses.
date = db.Column(db.Date, index=True, nullable=False)
arma_type = db.Column(db.String(50), index=True)
Constraints:
Data Integrity: Ensure that fields that should be unique or have certain constraints are properly defined. For example, if serial should be unique, enforce it at the database level.
serial = db.Column(db.String(50), unique=True)
Normalization:
Avoid Redundancy: If certain fields like arma_type have a limited set of possible values, consider creating a separate table for them and using foreign keys to enforce referential integrity.
3. Routes & Functionality
Strengths:
Comprehensive Endpoints: The application covers a wide range of CRUD operations, real-time updates via Server-Sent Events (SSE), and even Excel export functionality.
Use of Queues for Updates: Implementing a queue (update_queue) for managing real-time updates is a good approach to handle asynchronous tasks.
Areas for Improvement:
a. /get_unpacked_days Route:
Date Handling: Currently, dates are handled as strings which can lead to format inconsistencies. Using proper date types will enhance reliability.
b. /stream Route:
Resource Management: The current implementation uses an infinite loop with blocking queue.get. This can lead to resource exhaustion if not managed properly. Consider using background tasks or integrating with technologies like WebSockets for more efficient real-time communication.
c. /update_table Route:
Validation: There's minimal validation of incoming data. Implement thorough validation to ensure data integrity.
d. /generate_dl Route:
Concurrency Issues: When generating DL numbers, concurrent requests might lead to race conditions where two requests fetch the same counter value before incrementing. Consider using database transactions or locks to prevent this.
e. /export_excel Route:
Memory Consumption: Exporting large datasets to Excel can consume significant memory. Implement pagination or streaming responses for large exports.
Security: Ensure that only authorized users can export data to prevent data leakage.
f. Authentication & Authorization:
Current State: The application lacks robust authentication and authorization mechanisms. All users are treated without roles or permissions.
Recommendation: Implement Flask-Login or similar extensions to manage user sessions, roles, and permissions securely.
g. HTTP Methods:
Consistency: Ensure that routes use appropriate HTTP methods. For instance, fetching data should use GET, while creating or updating should use POST or PUT.
4. Error Handling & Logging
Strengths:
Basic Error Responses: The application returns JSON responses with error messages and appropriate HTTP status codes.
Areas for Improvement:
Centralized Error Handling:
Avoid Repetition: Instead of handling errors individually in each route, use Flask's error handlers to manage common HTTP errors (e.g., 400, 404, 500).
Sensitive Information: Ensure that error messages do not leak sensitive information about the server or database.
5. Security Considerations
Strengths:
Input Validation: Some routes perform basic input validation.
Areas for Improvement:
CSRF Protection:
Current State: Forms and POST requests lack Cross-Site Request Forgery (CSRF) protection.
Recommendation: Use Flask-WTF or implement CSRF tokens manually to protect against CSRF attacks.
from flask_wtf import CSRFProtect
csrf = CSRFProtect(app)
Authentication & Authorization:
Enhancement Needed: As mentioned earlier, implement proper user authentication and role-based access control to restrict sensitive operations.
Input Sanitization:
Prevent Injection Attacks: Ensure that all user inputs are sanitized to prevent SQL injection, although SQLAlchemy ORM already provides some protection.
Secure Cookies:
Cookie Flags: When setting cookies, use flags like HttpOnly, Secure, and SameSite to enhance security.
Data Transmission: Ensure that the application is served over HTTPS to protect data in transit, especially if handling sensitive information.
6. Performance Optimizations
Strengths:
Use of SQLAlchemy ORM: Facilitates efficient database interactions with lazy loading where appropriate.
Areas for Improvement:
Database Queries:
Eager Loading: For related objects like LoginHistory, consider using eager loading to reduce the number of database queries.
user = User.query.options(db.joinedload(User.login_history)).filter_by(username=name).first()
Caching:
Implement Caching: Utilize caching mechanisms (e.g., Redis, Memcached) for frequently accessed data to reduce database load and improve response times.
Pagination:
Handle Large Datasets: Implement pagination for routes that return large datasets to prevent performance degradation and excessive memory usage.
Asynchronous Tasks:
Background Processing: Use task queues like Celery for handling long-running tasks (e.g., generating Excel files) asynchronously.
7. Code Quality & Best Practices
Strengths:
Use of Flask Best Practices: The application follows several Flask best practices, such as using app.app_context() for database initialization and leveraging Flask's routing system effectively.
Areas for Improvement:
PEP 8 Compliance:
Formatting: Ensure that the code adheres to PEP 8 standards for readability. Tools like flake8 or black can help automate this process.
Magic Numbers & Strings:
Avoid Hardcoding: Instead of hardcoding strings like database URIs or specific army types ('RPA'), consider using configuration files or environment variables.
import os
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URI', 'sqlite:///table_data.db')
DRY Principle:
Reduce Repetition: If you find similar blocks of code across multiple routes (e.g., fetching a row by ID and date), abstract them into helper functions.
Docstrings: Add docstrings to functions and classes to explain their purpose and usage, making the code more maintainable and understandable.
@app.route('/update_graf', methods=['POST'])
def update_graf():
"""
Updates the 'dl_number' of a specific TableRow identified by 'id' and 'date'.
"""
...
8. Recommendations for Improvement
Based on the analysis above, here are actionable recommendations to enhance your application's robustness, security, and maintainability:
Refactor the Codebase:
Organize the application into multiple modules.
Separate concerns to make the codebase more manageable.
Enhance Database Models:
Use appropriate data types (Date, DateTime).
Implement indexing and constraints.
Consider normalization where applicable.
Implement Robust Authentication & Authorization:
Use Flask-Login or Flask-Security to manage user sessions and roles.
Protect sensitive routes to ensure only authorized users can access them.
Improve Error Handling:
Centralize error handling using Flask's error handlers.
Configure logging to capture essential information without exposing sensitive data.
Strengthen Security Measures:
Implement CSRF protection.
Sanitize all user inputs.
Serve the application over HTTPS.
Secure cookies with appropriate flags.
Optimize Performance:
Implement caching for frequently accessed data.
Use pagination for large datasets.
Offload long-running tasks to background workers using Celery or similar tools.
Adhere to Best Practices:
Ensure PEP 8 compliance for readability.
Use environment variables for configuration.
Avoid magic numbers and strings by defining constants or using configuration files.
Add type annotations and docstrings for better maintainability.
Testing:
Implement unit and integration tests to ensure that each component functions as expected.
Use testing frameworks like pytest to automate testing processes.
Documentation:
Maintain comprehensive documentation explaining the application's setup, functionalities, and usage.
Consider using tools like Sphinx for generating documentation from docstrings.
Deployment Considerations:
Use a production-ready web server like Gunicorn or uWSGI.
9. Final Thoughts
Your application demonstrates a solid foundation with essential functionalities implemented effectively. By addressing the areas of improvement outlined above, you can enhance the application's security, performance, and maintainability, ensuring it scales efficiently as your project grows.
If you have specific questions or need assistance with particular sections of the code, feel free to ask!