50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
from flask import render_template, abort, redirect, url_for, abort, flash, request, current_app, make_response, g
|
|
from . import news
|
|
|
|
from functools import lru_cache
|
|
import requests
|
|
import json
|
|
from dateutil.parser import parse
|
|
from dateutil.tz import tzutc
|
|
from facepy import GraphAPI
|
|
|
|
@lru_cache(maxsize=32)
|
|
def get_fb_token():
|
|
payload = {'grant_type': 'client_credentials', 'client_id': current_app.config['FB_APP_ID'], 'client_secret': current_app.config['FB_APP_SECRET']}
|
|
response = requests.post('https://graph.facebook.com/oauth/access_token?', params = payload)
|
|
fbjson = json.loads(response.text)
|
|
fbtoken = fbjson['access_token']
|
|
#current_app.logger.info("FB Token: {}".format(fbtoken))
|
|
return fbtoken
|
|
|
|
@news.app_template_filter('fbtime')
|
|
def fbtime(event_date):
|
|
UTC = tzutc()
|
|
dt = parse(event_date)
|
|
dt_utc = dt.astimezone(UTC) # Convert to UTC
|
|
return dt.strftime('%d %b %Y')
|
|
|
|
@news.route("/all", methods=['GET'])
|
|
def all():
|
|
graph = GraphAPI(get_fb_token())
|
|
#current_app.logger.info(get_fb_token.cache_info())
|
|
page_id = current_app.config['FB_PAGE_ID']
|
|
datas = graph.get(page_id+'/posts?fields=id,message,created_time,link,icon', page=True, retry=3)
|
|
posts = []
|
|
for data in datas:
|
|
posts.append(data)
|
|
content=posts[0]['data']
|
|
return render_template('news/facebook.html', result=content)
|
|
|
|
@news.route('/latest')
|
|
def latest():
|
|
graph = GraphAPI(get_fb_token())
|
|
page_id = current_app.config['FB_PAGE_ID']
|
|
latest = graph.get(page_id+'/posts?limit=2&fields=id,message,created_time,link', page=True, retry=3)
|
|
posts = []
|
|
for data in latest:
|
|
posts.append(data)
|
|
content=posts[0]['data']
|
|
return render_template('news/latest.html', result=content)
|
|
|