-
Notifications
You must be signed in to change notification settings - Fork 98
/
headlines.py
72 lines (49 loc) · 1.9 KB
/
headlines.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
#!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
import datetime
import requests
import feedparser
from flask import Flask, render_template, request, make_response
app = Flask(__name__)
RSS_FEED = {"zhihu": "https://www.zhihu.com/rss",
"netease": "http://news.163.com/special/00011K6L/rss_newsattitude.xml",
"songshuhui": "http://songshuhui.net/feed",
"ifeng": "http://news.ifeng.com/rss/index.xml"}
DEFAULTS = {'city': '北京',
'publication': 'songshuhui'}
WEATHERS = {"北京": 101010100,
"上海": 101020100,
"广州": 101280101,
"深圳": 101280601}
def get_value_with_fallback(key):
if request.args.get(key):
return request.args.get(key)
if request.cookies.get(key):
return request.cookies.get(key)
return DEFAULTS[key]
@app.route('/')
def home():
publication = get_value_with_fallback('publication')
city = get_value_with_fallback('city')
weather = get_weather(city)
articles = get_news(publication)
response = make_response(render_template('home.html', articles=articles,
weather=weather))
expires = datetime.datetime.now() + datetime.timedelta(days=365)
response.set_cookie('publication', publication, expires=expires)
response.set_cookie('city', city, expires=expires)
return response
def get_news(publication):
feed = feedparser.parse(RSS_FEED[publication])
return feed['entries']
def get_weather(city):
code = WEATHERS.get(city, 101010100)
url = "http://www.weather.com.cn/data/sk/{0}.html".format(code)
r = requests.get(url)
r.encoding = 'utf-8'
data = r.json()['weatherinfo']
return dict(city=data['city'], temperature=data['temp'],
description=data['WD'])
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000, debug=True)