main.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from flask import Flask, redirect, render_template, url_for, request, make_response, Markup
  2. import datetime
  3. from blog import Blog, Post
  4. from config import config, START_YEAR, SITE_TITLE
  5. from atom import make_feed
  6. from users import Users
  7. app = Flask(__name__)
  8. blog = Blog()
  9. users = Users()
  10. date = datetime.date.today()
  11. year_indicate = date.year if date.year == START_YEAR else f"{START_YEAR} - {date.year}"
  12. make_feed(blog.get_all())
  13. @app.route('/feeds')
  14. def get_feed():
  15. rss_xml = render_template('atom.xml')
  16. response = make_response(rss_xml)
  17. response.headers['Content-Type'] = 'application/rss+xml'
  18. return response
  19. @app.errorhandler(404)
  20. def not_found(e):
  21. return render_template("404.html")
  22. @app.route("/")
  23. def get_home():
  24. return render_template(
  25. 'index.html',
  26. title=SITE_TITLE,
  27. year=year_indicate,
  28. page=1,
  29. users=users,
  30. pages=blog.get_pages_count(),
  31. posts=blog.get_by_page(page=1)
  32. )
  33. @app.route("/page/<int:page>")
  34. def get_blog_page(page):
  35. pages = blog.get_pages_count()
  36. if page > len(pages):
  37. return render_template('404.html')
  38. return render_template(
  39. 'index.html',
  40. title=f'{SITE_TITLE} - page {page}',
  41. year=year_indicate,
  42. page=page,
  43. users=users,
  44. pages=pages,
  45. posts=blog.get_by_page(page=page)
  46. )
  47. @app.route("/post/add")
  48. def add_post():
  49. blog.add_post(Post(
  50. id=len(blog.get_all())+1,
  51. user_id=2,
  52. title='Another post',
  53. body=Markup(
  54. 'Hello my <span style="color:red">friends</span>. This is test post')
  55. ))
  56. make_feed(blog.get_all())
  57. return redirect(url_for('get_home'))
  58. @app.route("/post/<int:post_id>")
  59. def get_post(post_id):
  60. post = blog.get_post_by_id(post_id)
  61. if post:
  62. username = users.get_user_by_id(post.user_id).username
  63. return render_template(
  64. 'post.html',
  65. title=f'{SITE_TITLE} - {post.title}',
  66. year=year_indicate,
  67. username=username,
  68. post=post)
  69. else:
  70. return render_template('404.html')
  71. @app.route("/secret")
  72. def get_login():
  73. return render_template('login.html')
  74. @app.route("/profile")
  75. def get_profile():
  76. return render_template('profile.html')
  77. @app.route("/dashboard")
  78. def get_dashboard():
  79. return render_template('dashboard.html')
  80. @app.route("/username/<name>=<int:age>")
  81. def hello_user(name, age):
  82. return f"Hello {name} {age} y.o."
  83. if __name__ == "__main__":
  84. app.config.from_object(config)
  85. app.run()