Skip to content

Latest commit

Β 

History

369 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Sistema GCI Web - Flask + SQL Server

Sistema web para gerenciamento de estudos de viabilidade elΓ©trica, desenvolvido em Flask com SQL Server.

πŸš€ CaracterΓ­sticas

  • Performance Otimizada: Evita o problema N+1 atravΓ©s de relacionamentos SQLAlchemy bem configurados
  • SQL Server Nativo: ConexΓ£o otimizada com SQL Server usando pyodbc
  • API RESTful: Endpoints JSON para integraΓ§Γ£o e frontend
  • Pool de ConexΓ΅es: Gerenciamento inteligente de conexΓ΅es com banco
  • ConfiguraΓ§Γ£o FlexΓ­vel: Suporte a mΓΊltiplos ambientes via variΓ‘veis de ambiente

πŸ“‹ PrΓ©-requisitos

Sistema

  • Python 3.8+
  • SQL Server 2016+ ou SQL Server Express
  • Driver ODBC do SQL Server

Driver ODBC

Windows

# Baixe e instale de:
# https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-server

Linux (Ubuntu/Debian)

sudo apt-get update
sudo apt-get install -y curl

# Adicionar repositΓ³rio Microsoft
curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -
curl https://packages.microsoft.com/config/ubuntu/$(lsb_release -rs)/prod.list > /etc/apt/sources.list.d/mssql-release.list

# Instalar driver
sudo apt-get update
sudo ACCEPT_EULA=Y apt-get install -y msodbcsql17
sudo apt-get install -y unixodbc-dev

macOS

brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
HOMEBREW_NO_ENV_FILTERING=1 ACCEPT_EULA=Y brew install msodbcsql17 mssql-tools

⚑ Instalação RÑpida

OpΓ§Γ£o 1: Setup Automatizado

# Clone o repositΓ³rio
git clone <repository-url>
cd gci-web

# Execute o setup automatizado
python setup.py

# Edite as configuraΓ§Γ΅es
nano .env

# Ative o ambiente virtual
source venv/bin/activate  # Linux/Mac
# ou
venv\Scripts\activate     # Windows

# Execute a aplicaΓ§Γ£o
python app.py

OpΓ§Γ£o 2: InstalaΓ§Γ£o Manual

# 1. Criar ambiente virtual
python -m venv venv
source venv/bin/activate  # Linux/Mac
# ou venv\Scripts\activate (Windows)

# 2. Instalar dependΓͺncias
pip install -r requirements.txt

# 3. Configurar variΓ‘veis de ambiente
cp .env.example .env
nano .env  # Editar configuraΓ§Γ΅es

# 4. Testar conexΓ£o
python database.py

# 5. Criar tabelas
flask init-db

# 6. Executar aplicaΓ§Γ£o
python app.py

βš™οΈ ConfiguraΓ§Γ£o

VariΓ‘veis de Ambiente Principais

Edite o arquivo .env com suas configuraΓ§Γ΅es:

# SQL Server
SQLSERVER_HOST=localhost
SQLSERVER_PORT=1433
SQLSERVER_DATABASE=atlas_db
SQLSERVER_USERNAME=sa
SQLSERVER_PASSWORD=YourPassword123!

# Driver (ajuste conforme sua instalaΓ§Γ£o)
SQLSERVER_DRIVER=ODBC Driver 17 for SQL Server

# Flask
SECRET_KEY=sua-chave-secreta-aqui
FLASK_DEBUG=false

ConfiguraΓ§Γ΅es AvanΓ§adas

# Pool de conexΓ΅es
SQLALCHEMY_POOL_SIZE=10
SQLALCHEMY_MAX_OVERFLOW=20
SQLALCHEMY_POOL_TIMEOUT=30
SQLALCHEMY_POOL_RECYCLE=3600

# SSL/Certificados
TRUST_SERVER_CERTIFICATE=yes
SQLSERVER_ENCRYPT=no

# Timeouts
CONNECTION_TIMEOUT=30
COMMAND_TIMEOUT=30

πŸ—„οΈ Estrutura do Banco de Dados

O sistema utiliza o schema atlas no SQL Server com as seguintes tabelas principais:

  • estudos: Estudos de viabilidade
  • empresas: Empresas solicitantes
  • usuarios: UsuΓ‘rios do sistema
  • regionais: Regionais da empresa
  • alternativas: Alternativas tΓ©cnicas
  • anexos: Arquivos anexados
  • status_estudo: HistΓ³rico de status

CriaΓ§Γ£o do Schema

-- Execute no SQL Server
CREATE DATABASE atlas_db;
USE atlas_db;

-- O schema serΓ‘ criado automaticamente pelo Flask
-- Ou execute o arquivo atlas_schema.sql

πŸ”§ Comandos DisponΓ­veis

Flask CLI

# Testar conexΓ£o
flask test-db

# InformaΓ§Γ΅es do banco
flask db-info

# Criar/recriar tabelas
flask init-db

Scripts Python

# Teste standalone de conexΓ£o
python database.py

# Verificar apenas requisitos
python setup.py --check

# Instalar apenas dependΓͺncias
python setup.py --deps

πŸ“š API Endpoints

Estudos

GET    /api/estudos              # Listar estudos (paginado)
GET    /api/estudos/{id}         # Obter estudo especΓ­fico
POST   /api/estudos              # Criar estudo
PUT    /api/estudos/{id}         # Atualizar estudo
DELETE /api/estudos/{id}         # Remover estudo

Dashboard

GET    /api/dashboard/stats      # EstatΓ­sticas gerais

Sistema

GET    /                         # Status da aplicaΓ§Γ£o
GET    /health                   # Health check

Exemplos de Uso

Listar estudos com paginaΓ§Γ£o

curl "http://localhost:5000/api/estudos?page=1&per_page=20"

Obter estudo especΓ­fico

curl "http://localhost:5000/api/estudos/123"

πŸš€ Performance e OtimizaΓ§Γ΅es

PrevenΓ§Γ£o do Problema N+1

O sistema utiliza estratΓ©gias otimizadas para evitar o problema N+1:

# ❌ ProblemÑtico - gera N+1 queries
estudos = Estudo.query.all()
for estudo in estudos:
    print(estudo.regional.regional)  # Query para cada estudo

# βœ… Otimizado - apenas 1 query
estudos = Estudo.query.options(
    db.joinedload(Estudo.regional)
).all()
for estudo in estudos:
    print(estudo.regional.regional)  # Dados jΓ‘ carregados

MΓ©todos Otimizados

# Carregar estudo com todos relacionamentos
estudo = Estudo.get_with_all_relations(estudo_id)

# Listar com relacionamentos bΓ‘sicos
estudos = Estudo.get_list_with_basic_relations().all()

# PaginaΓ§Γ£o otimizada
from models import get_estudos_com_paginacao
estudos = get_estudos_com_paginacao(page=1, per_page=20)

πŸ”’ SeguranΓ§a

ConexΓ£o com Banco

  • Pool de conexΓ΅es com timeout
  • ParΓ’metros escapados automaticamente
  • Isolamento de transaΓ§Γ΅es
  • ConexΓ΅es SSL configurΓ‘veis

AplicaΓ§Γ£o

  • Chave secreta para sessΓ΅es
  • ValidaΓ§Γ£o de entrada
  • CORS configurΓ‘vel
  • Headers de seguranΓ§a

πŸ“Š Monitoramento

Logs

# Habilitar logs SQL (apenas desenvolvimento)
SQLALCHEMY_ECHO=true

# Configurar nΓ­vel de log
LOG_LEVEL=INFO

Health Check

curl http://localhost:5000/health

MΓ©tricas do Pool de ConexΓ΅es

# No cΓ³digo da aplicaΓ§Γ£o
from database import db_manager
info = db_manager.db.engine.pool.status()

🐳 Deploy

Docker (Opcional)

FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 5000

CMD ["gunicorn", "--bind", "0.0.0.0:5000", "app:create_app()"]

ProduΓ§Γ£o

# Usar Gunicorn para produΓ§Γ£o
pip install gunicorn
gunicorn --workers 4 --bind 0.0.0.0:5000 "app:create_app()"

πŸ› οΈ Desenvolvimento

Estrutura do Projeto

gci-web/
β”œβ”€β”€ app.py              # AplicaΓ§Γ£o Flask principal
β”œβ”€β”€ models.py           # Modelos SQLAlchemy
β”œβ”€β”€ database.py         # ConexΓ£o SQL Server
β”œβ”€β”€ setup.py            # Script de instalaΓ§Γ£o
β”œβ”€β”€ requirements.txt    # DependΓͺncias Python
β”œβ”€β”€ .env.example        # Exemplo de configuraΓ§Γ£o
β”œβ”€β”€ atlas_schema.sql   # Schema do banco
└── README.md          # Esta documentaΓ§Γ£o


β”œβ”€β”€ app/
β”‚ β”œβ”€β”€ alternativa
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ alternativa
β”‚ β”‚ β”‚ β”‚ └── alternativa.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ api
β”‚ β”‚ β”œβ”€β”€ __init__.py  (NΓ£o tem nada)
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ auth
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ auth
β”‚ β”‚ β”‚ β”‚ └── login.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ cadastro
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ cadastro
β”‚ β”‚ β”‚ β”‚ β”œβ”€β”€ cadastrar_estudo.html
β”‚ β”‚ β”‚ β”‚ └── editar_estudo.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ circuitos
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ deploy
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ restart_atlas.sh
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ listar
β”‚ β”‚ β”œβ”€β”€ static
β”‚ β”‚ β”‚ β”œβ”€β”€ css
β”‚ β”‚ β”‚ β”‚ └── listar_estudos.css
β”‚ β”‚ β”‚ └── js
β”‚ β”‚ β”‚ β”‚ └── listar_estudos.js
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ listar
β”‚ β”‚ β”‚ β”‚ └── listar.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ main
β”‚ β”‚ β”œβ”€β”€ static
β”‚ β”‚ β”‚ β”œβ”€β”€ css
β”‚ β”‚ β”‚ β”‚ └── listar.css
β”‚ β”‚ β”‚ β”œβ”€β”€ images
β”‚ β”‚ β”‚ β”‚ └── background.png
β”‚ β”‚ β”‚ └── js
β”‚ β”‚ β”‚ β”‚ └── listar.js
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ main
β”‚ β”‚ β”‚ β”‚ └── index.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ municipios
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ └── municipios.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ static
β”‚ β”‚ β”œβ”€β”€ css
β”‚ β”‚ β”‚ └── listar_unificado.css
β”‚ β”‚ β”œβ”€β”€ js
β”‚ β”‚ β”‚ └── listar_unificado.js
β”‚ β”œβ”€β”€ status
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ status
β”‚ β”‚ β”‚ β”‚ └── status.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ subestacoes
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ editar_subestacao.html
β”‚ β”‚ β”‚ β”œβ”€β”€ listar.html
β”‚ β”‚ β”‚ β”œβ”€β”€ nova_subestacao.html
β”‚ β”‚ β”‚ └── subestacoes.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”œβ”€β”€ base.html
β”‚ β”‚ β”œβ”€β”€ lista_generica.html
β”‚ β”‚ └── listar_unificado.html
β”‚ β”œβ”€β”€ user
β”‚ β”‚ β”œβ”€β”€ templates
β”‚ β”‚ β”‚ β”œβ”€β”€ user
β”‚ β”‚ β”‚ β”‚ └── user.html
β”‚ β”‚ β”œβ”€β”€ __init__.py
β”‚ β”‚ β”œβ”€β”€ forms.py
β”‚ β”‚ └── routes.py
β”‚ β”œβ”€β”€ __init__.py
β”‚ β”œβ”€β”€ config.py
β”‚ β”œβ”€β”€ database.py
β”‚ β”œβ”€β”€ atlas_schema.sql
β”‚ β”œβ”€β”€ insert into tables.sql
β”‚ β”œβ”€β”€ models.py
β”‚ β”œβ”€β”€ schema.sql
β”œβ”€β”€ run.py
β”œβ”€β”€ .env
β”œβ”€β”€ .gitignore
β”œβ”€β”€ LICENSE
β”œβ”€β”€ README.md
β”œβ”€β”€ todo.py
β”œβ”€β”€ wsgi.py

Adicionando Novos Models

# Em models.py
class NovoModel(db.Model):
    __tablename__ = 'nova_tabela'
    __table_args__ = {'schema': 'atlas'}
    
    id = db.Column(db.BigInteger, primary_key=True)
    # ... outros campos

Executando Testes

# Instalar dependΓͺncias de teste
pip install pytest pytest-flask

# Executar testes
pytest

πŸ”§ Troubleshooting

Problemas Comuns

Erro: "Driver not found"

# Verifique drivers instalados
python -c "import pyodbc; print(pyodbc.drivers())"

# Instale driver correto (veja seΓ§Γ£o prΓ©-requisitos)

Erro: "Login failed"

# Verifique credenciais no .env
# Teste conexΓ£o manual no SQL Server
sqlcmd -S localhost -U sa -P YourPassword123!

Erro: "Connection timeout"

# Verifique se SQL Server aceita conexΓ΅es TCP/IP
# SQL Server Configuration Manager > Protocols > TCP/IP = Enabled
# Reinicie o serviΓ§o SQL Server

Performance lenta

# Habilite logs para investigar
SQLALCHEMY_ECHO=true

# Verifique Γ­ndices no banco
# Use mΓ©todos otimizados dos models

Logs Úteis

# Ver logs de conexΓ£o
tail -f app.log

# Logs do SQL Server
# Windows: Event Viewer > Windows Logs > Application
# Linux: /var/log/mssql/

πŸ“ž Suporte

Para dΓΊvidas e problemas:

  1. Verifique a documentaΓ§Γ£o acima
  2. Execute o diagnΓ³stico: python setup.py --check
  3. Teste a conexΓ£o: flask test-db
  4. Verifique os logs da aplicaΓ§Γ£o

πŸ“„ LicenΓ§a

[Adicione informaΓ§Γ΅es de licenΓ§a aqui]


🎯 Sistema GCI Web - Desenvolvido para mÑxima performance com SQL Server

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages