Versão 0.1

parent 7c735d75
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
# Caminho do banco
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'animais.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# =========================
# MODELO
# =========================
class Animal(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
nome = db.Column(db.String(100), nullable=False)
especie = db.Column(db.String(100), nullable=False)
idade = db.Column(db.Integer, nullable=False)
peso = db.Column(db.Float, nullable=False)
def __repr__(self):
return f'<Animal {self.nome}>'
# =========================
# FUNÇÃO PARA GERAR .MD
# =========================
def gerar_markdown():
pasta_atual = os.path.abspath(os.path.dirname(__file__))
pasta_pai = os.path.dirname(pasta_atual)
caminho_md = os.path.join(pasta_pai, 'banco.md')
animais = Animal.query.all()
with open(caminho_md, 'w', encoding='utf-8') as f:
f.write("# Relatório de Animais\n\n")
if not animais:
f.write("Nenhum animal cadastrado.\n")
else:
for a in animais:
f.write(f"## {a.nome}\n")
f.write(f"- Espécie: {a.especie}\n")
f.write(f"- Idade: {a.idade} anos\n")
f.write(f"- Peso: {a.peso} kg\n\n")
# =========================
# ROTAS
# =========================
@app.route('/')
def index():
animais = Animal.query.all()
return render_template('index.html', animais=animais)
@app.route('/cadastro', methods=['GET', 'POST'])
def cadastro():
if request.method == 'POST':
try:
novo = Animal(
nome=request.form['nome'],
especie=request.form['especie'],
idade=int(request.form['idade']),
peso=float(request.form['peso'])
)
db.session.add(novo)
db.session.commit()
gerar_markdown()
return redirect(url_for('index'))
except Exception as e:
db.session.rollback()
return f"Erro ao cadastrar: {str(e)}"
return render_template('cadastro.html')
@app.route('/delete/<int:id>')
def delete(id):
animal = Animal.query.get_or_404(id)
try:
db.session.delete(animal)
db.session.commit()
gerar_markdown()
return redirect(url_for('index'))
except:
db.session.rollback()
return "Erro ao deletar"
# =========================
# INICIALIZAÇÃO
# =========================
if __name__ == '__main__':
with app.app_context():
db.create_all()
gerar_markdown()
app.run(debug=True)
\ No newline at end of file
# Relatório de Animais
Nenhum animal cadastrado.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment