app.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import sqlite3
  2. from datetime import datetime
  3. from flask import Flask, render_template, redirect, url_for, request
  4. from flask_sqlalchemy import SQLAlchemy
  5. from flask_paginate import Pagination
  6. # from sqlalchemy import Column, Integer, String
  7. # from sqlalchemy.ext.declarative import declarative_base
  8. app = Flask(__name__)
  9. app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///news.db'
  10. db = SQLAlchemy(app)
  11. class News(db.Model):
  12. __tablename__ = 'news'
  13. nid = db.Column(db.String, primary_key=True)
  14. author = db.Column(db.Unicode)
  15. title = db.Column(db.Unicode)
  16. body = db.Column(db.Unicode)
  17. published = db.Column(db.String)
  18. last_modified = db.Column(db.String)
  19. display = db.Column(db.Unicode)
  20. @property
  21. def canonical_url(self):
  22. return url_for('news', year=self.published_datetime.year, month=self.published_datetime.month, nid=self.nid)
  23. @property
  24. def published_datetime(self):
  25. return datetime.fromtimestamp(self.published)
  26. @property
  27. def published_str(self):
  28. return str(self.published_datetime)
  29. def __repr__(self):
  30. return "<News(%s)>" % (self.nid)
  31. @app.route('/')
  32. def home():
  33. return 'homepage'
  34. @app.route('/search/')
  35. def search_home():
  36. return 'cerca cerca'
  37. @app.route('/search/by-month/<int:year>/<int:month>')
  38. def search_by_month(year, month):
  39. # TODO: proper pagination
  40. page = int(request.args.get('page', '1')) - 1
  41. first = page * 50
  42. last = first + 50
  43. d = datetime(year=year, month=month, day=1)
  44. ts_from = int(d.timestamp())
  45. if month < 12:
  46. d = datetime(year=year, month=month+1, day=1)
  47. else:
  48. d = datetime(year=year+1, month=1, day=1)
  49. ts_to = int(d.timestamp())
  50. news = News.query.filter(News.published >= ts_from, News.published < ts_to).order_by('published')
  51. pagination = Pagination(page=page, total=news.count(), per_page=50)
  52. news = news[first:last]
  53. return render_template('search_results.html', results=news, pagination=pagination)
  54. @app.route('/news/<int:nid>')
  55. def news_by_nid(nid):
  56. n = News.query.get(str(nid))
  57. return redirect(n.canonical_url)
  58. @app.route('/news/<year>/<month>/<int:nid>.php')
  59. def news(year, month, nid):
  60. n = News.query.get(str(nid))
  61. return render_template('news.html', n=n)