-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
105 lines (77 loc) · 2.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import os
from datetime import datetime
from dotenv import load_dotenv
from flask import Flask
from flask import abort, redirect, render_template, request, url_for
from flask_caching import Cache
from newsapi import NewsApiClient
load_dotenv()
config = {
"DEBUG": True,
"CACHE_TYPE": "SimpleCache",
"CACHE_DEFAULT_TIMEOUT": 300
}
app = Flask(__name__, template_folder='templates')
app.config.from_mapping(config)
cache = Cache(app, config=config)
API_KEY = os.getenv("API_KEY", None)
client = NewsApiClient(api_key=API_KEY)
CATEGORIES = ['business', 'entertainment', 'general', 'healths', 'sports', 'technology', 'science']
@app.template_filter('date_time')
def date(timestamp):
"""
Returns the date formatted string for the given timestamp.
"""
format_datetime = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ')
return format_datetime.strftime('%B %d, %Y %I:%M %p')
@app.route("/")
@app.route("/page=<int:page>")
@cache.cached(timeout=300)
def index(page=1, page_size=20):
try:
data = client.get_top_headlines(page=page, page_size=page_size)
news_article = data["articles"]
return render_template('index.html', article=news_article, page=page)
except Exception as e:
return abort(500)
@app.route("/category/<string:category>")
@app.route("/category/<string:category>/page=<int:page>")
@cache.cached(timeout=300)
def news_category(category=None, page=1, page_size=16):
if category in CATEGORIES:
try:
data = client.get_everything(q=category, page=page, page_size=16)
news_article = data["articles"]
return render_template(
"category.html", article=news_article, category=category, page=page
)
except Exception as e:
return abort(500)
return abort(404)
@app.route("/news/search")
def search_news(page_size=20):
query = request.args.get('q')
if not query:
return abort(404)
try:
data = client.get_everything(q=query, page_size=page_size)
news_article = data["articles"]
except Exception as e:
return abort(500)
return render_template("search.html", article=news_article)
@app.errorhandler(404)
def not_found(e):
return render_template(
"error.html",
error_message="404 Page Not Found"
,status=404
), 404
@app.errorhandler(500)
def server_error(e):
return render_template(
"error.html",
error_message="500 Internal Server Error"
,status=500
), 500
if __name__ == '__main__':
app.run()