Commit 7c78a829 by bricioso

atualizei

parent ec7e34f2
from flask import Flask, render_template, request, redirect from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy from models import db, Animal
import os
app = Flask(__name__) app = Flask(__name__)
# CONFIGURAÇÃO DO BANCO # Configuração do banco de dados real
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///fazenda.db' basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'fazenda.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app) db.init_app(app)
# TABELA # Cria o banco de dados e as colunas (nome, especie, idade, peso)
class Animal(db.Model): with app.app_context():
id = db.Column(db.Integer, primary_key=True) db.create_all()
nome = db.Column(db.String(100))
tipo = db.Column(db.String(100))
idade = db.Column(db.Integer)
# PÁGINA INICIAL
@app.route('/') @app.route('/')
def index(): def index():
animais = Animal.query.all() animais = Animal.query.all()
return render_template('index.html', animais=animais) return render_template('index.html', animais=animais)
# CADASTRAR @app.route('/cadastro')
def cadastro():
return render_template('cadastro.html')
@app.route('/adicionar', methods=['POST']) @app.route('/adicionar', methods=['POST'])
def adicionar(): def adicionar():
# O segredo está aqui: os nomes entre [''] devem ser IGUAIS ao 'name' do HTML
nome = request.form['nome'] nome = request.form['nome']
tipo = request.form['tipo'] especie = request.form['especie'] # Antes estava 'tipo', por isso dava erro
idade = request.form['idade'] idade = request.form['idade']
peso = request.form['peso'] # Agora estamos pegando o peso também
novo_animal = Animal( novo_animal = Animal(
nome=nome, nome=nome,
tipo=tipo, especie=especie,
idade=idade idade=int(idade),
peso=float(peso)
) )
db.session.add(novo_animal) db.session.add(novo_animal)
db.session.commit() db.session.commit()
return redirect('/') return redirect(url_for('index'))
# EXCLUIR
@app.route('/excluir/<int:id>') @app.route('/excluir/<int:id>')
def excluir(id): def excluir(id):
animal = Animal.query.get(id) animal = Animal.query.get_or_404(id)
if animal:
db.session.delete(animal) db.session.delete(animal)
db.session.commit() db.session.commit()
return redirect(url_for('index'))
return redirect('/')
if __name__ == '__main__': if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True) app.run(debug=True)
\ No newline at end of file
File added
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