Created
April 20, 2016 16:55
-
-
Save ondoheer/c26b3824e286e7ea9a4d260abe62a2ee to your computer and use it in GitHub Desktop.
Basic Flask Crud
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AdminFAQView(AdminView): | |
def __init__(self): | |
self.form = FAQQuestionForm() | |
self.questions = db.session.query(Question.id, Question.question).all() | |
def get(self, question_id=None): | |
form = self.form | |
questions = self.questions | |
if not question_id: | |
return render_template( | |
"admin/faq.html", | |
questions=questions, | |
form=form | |
) | |
else: | |
question = db.session.query(Question).get(question_id) | |
if not question: | |
flash("No existe esa pregunta", "warning") | |
return redirect(url_for("admin.faq")) | |
if not "delete" in request.path: | |
form.question.data = question.question | |
form.answer.data = question.answer | |
return render_template( | |
"admin/faq.html", | |
single=question, | |
questions=questions, | |
form=form | |
) | |
elif "delete" in request.path: | |
db.session.delete(question) | |
db.session.commit() | |
flash("Pregunta del FAQ borrada", "warning") | |
return redirect(url_for("admin.faq")) | |
def post(self, question_id=""): | |
form = self.form | |
if form.validate_on_submit(): | |
if not question_id: | |
question = Question() | |
else: | |
question = db.session.query(Question).get(question_id) | |
question.question = form.question.data | |
question.answer = form.answer.data | |
db.session.add(question) | |
db.session.commit() | |
flash("La pregunta se guardó con éxito", "success") | |
return redirect(url_for("admin.faq")) | |
flash("El formulario no validó: {}".format(form.errors), "alert") | |
return redirect(url_for("admin.faq")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Si quitas el
.all()
en la línea 5, el query se vuelve lazy, es decir que no se ejecuta hasta que lo iteras.Hay varias casos en que no necesitas ejecutar ese query para nada