Commit 4dda1a6d by Hiago Rafael

po

parent 3bd092d4
from flask import Flask, render_template, request, redirect from flask import Flask, render_template, request, redirect
from models import Animal from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__) app = Flask(__name__)
animais = [] # CONFIGURAÇÃO DO BANCO
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///fazenda.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# TABELA
class Animal(db.Model):
id = db.Column(db.Integer, primary_key=True)
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()
return render_template('index.html', animais=animais) return render_template('index.html', animais=animais)
@app.route('/cadastro') # CADASTRAR
def cadastro():
return render_template('cadastro.html')
@app.route('/adicionar', methods=['POST']) @app.route('/adicionar', methods=['POST'])
def adicionar(): def adicionar():
nome = request.form['nome'] nome = request.form['nome']
tipo = request.form['tipo'] tipo = request.form['tipo']
idade = request.form['idade'] idade = request.form['idade']
novo_animal = Animal(nome, tipo, idade) novo_animal = Animal(
animais.append(novo_animal) nome=nome,
tipo=tipo,
idade=idade
)
db.session.add(novo_animal)
db.session.commit()
return redirect('/') return redirect('/')
# EXCLUIR
@app.route('/excluir/<int:id>') @app.route('/excluir/<int:id>')
def excluir(id): def excluir(id):
if 0 <= id < len(animais): animal = Animal.query.get(id)
animais.pop(id)
if animal:
db.session.delete(animal)
db.session.commit()
return redirect('/') 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
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