app.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from flask import Flask, render_template, url_for, request, redirect
  2. from flask_sqlalchemy import SQLAlchemy
  3. from datetime import datetime
  4. app = Flask(__name__)
  5. app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///test.db"
  6. app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
  7. db = SQLAlchemy(app)
  8. class Todo(db.Model):
  9. id = db.Column(db.Integer, primary_key=True)
  10. content = db.Column(db.String(200), nullable=False)
  11. completed = db.Column(db.Integer, default=0)
  12. pub_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
  13. def __repr__(self):
  14. return "<Task %r>" % self.id
  15. @app.route("/", methods=["POST", "GET"])
  16. def index():
  17. if request.method == "POST":
  18. task_content = request.form["task"]
  19. new_task = Todo(content=task_content)
  20. try:
  21. db.session.add(new_task)
  22. db.session.commit()
  23. return redirect("/")
  24. except:
  25. return "There is an issue"
  26. else:
  27. tasks = Todo.query.order_by(Todo.pub_date).all()
  28. return render_template("index.html", tasks=tasks)
  29. @app.route("/delete/<int:id>")
  30. def delete(id):
  31. task = Todo.query.get_or_404(id)
  32. try:
  33. db.session.delete(task)
  34. db.session.commit()
  35. return redirect("/")
  36. except:
  37. return "This is an Problem while deleting"
  38. @app.route("/update/<int:id>", methods=["POST", "GET"])
  39. def update(id):
  40. task = Todo.query.get_or_404(id)
  41. if request.method == "POST":
  42. task.content = request.form["task"]
  43. try:
  44. db.session.commit()
  45. return redirect("/")
  46. except:
  47. return "There is an issue"
  48. else:
  49. tasks = Todo.query.order_by(Todo.pub_date).all()
  50. return render_template("index.html", update_task=task, tasks=tasks)
  51. if __name__ == "__main__":
  52. app.run(debug=True)