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 facepy import GraphAPI @lru_cache(maxsize=8) 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.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)