Sistema web para gerenciamento de estudos de viabilidade elΓ©trica, desenvolvido em Flask com SQL Server.
- 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
- Python 3.8+
- SQL Server 2016+ ou SQL Server Express
- Driver ODBC do SQL Server
# Baixe e instale de:
# https://docs.microsoft.com/en-us/sql/connect/odbc/download-odbc-driver-for-sql-serversudo 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-devbrew 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# 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# 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.pyEdite 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# 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=30O 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
-- 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# Testar conexΓ£o
flask test-db
# InformaΓ§Γ΅es do banco
flask db-info
# Criar/recriar tabelas
flask init-db# Teste standalone de conexΓ£o
python database.py
# Verificar apenas requisitos
python setup.py --check
# Instalar apenas dependΓͺncias
python setup.py --depsGET /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 estudoGET /api/dashboard/stats # EstatΓsticas geraisGET / # Status da aplicaΓ§Γ£o
GET /health # Health checkcurl "http://localhost:5000/api/estudos?page=1&per_page=20"curl "http://localhost:5000/api/estudos/123"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# 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)- Pool de conexΓ΅es com timeout
- ParΓ’metros escapados automaticamente
- Isolamento de transaΓ§Γ΅es
- ConexΓ΅es SSL configurΓ‘veis
- Chave secreta para sessΓ΅es
- ValidaΓ§Γ£o de entrada
- CORS configurΓ‘vel
- Headers de seguranΓ§a
# Habilitar logs SQL (apenas desenvolvimento)
SQLALCHEMY_ECHO=true
# Configurar nΓvel de log
LOG_LEVEL=INFOcurl http://localhost:5000/health# No cΓ³digo da aplicaΓ§Γ£o
from database import db_manager
info = db_manager.db.engine.pool.status()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()"]# Usar Gunicorn para produΓ§Γ£o
pip install gunicorn
gunicorn --workers 4 --bind 0.0.0.0:5000 "app:create_app()"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
# Em models.py
class NovoModel(db.Model):
__tablename__ = 'nova_tabela'
__table_args__ = {'schema': 'atlas'}
id = db.Column(db.BigInteger, primary_key=True)
# ... outros campos# Instalar dependΓͺncias de teste
pip install pytest pytest-flask
# Executar testes
pytest# Verifique drivers instalados
python -c "import pyodbc; print(pyodbc.drivers())"
# Instale driver correto (veja seΓ§Γ£o prΓ©-requisitos)# Verifique credenciais no .env
# Teste conexΓ£o manual no SQL Server
sqlcmd -S localhost -U sa -P YourPassword123!# Verifique se SQL Server aceita conexΓ΅es TCP/IP
# SQL Server Configuration Manager > Protocols > TCP/IP = Enabled
# Reinicie o serviΓ§o SQL Server# Habilite logs para investigar
SQLALCHEMY_ECHO=true
# Verifique Γndices no banco
# Use mΓ©todos otimizados dos models# Ver logs de conexΓ£o
tail -f app.log
# Logs do SQL Server
# Windows: Event Viewer > Windows Logs > Application
# Linux: /var/log/mssql/Para dΓΊvidas e problemas:
- Verifique a documentaΓ§Γ£o acima
- Execute o diagnΓ³stico:
python setup.py --check - Teste a conexΓ£o:
flask test-db - Verifique os logs da aplicaΓ§Γ£o
[Adicione informaΓ§Γ΅es de licenΓ§a aqui]
π― Sistema GCI Web - Desenvolvido para mΓ‘xima performance com SQL Server