Instantly share code, notes, and snippets.
Created
February 12, 2018 16:58
-
Star
0
(0)
You must be signed in to star a gist -
Fork
0
(0)
You must be signed in to fork a gist
-
Save darwing1210/4ccc076037f7724493578e5c57530e7d to your computer and use it in GitHub Desktop.
Django Template tags to get posts from Facebook, Twitter, Instagram and YouTube.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
import json | |
import twitter | |
from datetime import datetime | |
from django.conf import settings | |
from django import template | |
register = template.Library() | |
@register.inclusion_tag('widget/_widget-facebook-post.html') | |
def get_facebook_posts(posts=1, fb_page_name): | |
base_url = 'https://graph.facebook.com' | |
context = {} | |
if settings.FACEBOOK_APP_ID and settings.FACEBOOK_SECRET_KEY: | |
try: | |
token_query = json.loads( | |
urllib.request.urlopen( | |
'{0}/oauth/access_token?client_id={1}&client_secret={2}&' | |
'grant_type=client_credentials'.format( | |
base_url, | |
settings.FACEBOOK_APP_ID, | |
settings.FACEBOOK_SECRET_KEY) | |
).read().decode('utf8')) | |
token = token_query.get('access_token') | |
if token: | |
graph_fields = ",".join([ | |
'id', | |
'message', | |
'created_time', | |
'name', | |
'type', | |
'link', | |
'object_id', | |
'full_picture', | |
'from', | |
]) | |
fb_query = json.loads( | |
urllib.request.urlopen( | |
'{0}/v2.12/{1}/posts?fields={2}&limit={3}&access_token={4}'.format( | |
base_url, fb_page_name, graph_fields, str(posts), token) | |
).read().decode('utf8') | |
) | |
context['data'] = fb_query.get('data') | |
for data in context['data']: | |
data['created_time'] = datetime.strptime( | |
data['created_time'], '%Y-%m-%dT%H:%M:%S%z') | |
except Exception as e: | |
print("Error Getting Facebook Posts", e) | |
return context | |
@register.inclusion_tag('widget/_widget-twitter-posts.html') | |
def get_twitter_posts(posts=1, twitter_user): | |
context = {} | |
try: | |
api = twitter.Api( | |
consumer_key=settings.TWITTER_CONSUMER_KEY, | |
consumer_secret=settings.TWITTER_SECRET_CONSUMER, | |
access_token_key=settings.TWITTER_ACCESS_TOKEN, | |
access_token_secret=settings.TWITTER_SECRET_TOKEN) | |
twitter_data = api.GetUserTimeline( | |
screen_name=twitter_user, | |
include_rts=True, | |
exclude_replies=True, | |
trim_user=False, | |
count=posts) | |
for data in twitter_data: | |
data.created_at = datetime.strptime( | |
data.created_at, '%a %b %d %H:%M:%S %z %Y') | |
context['tweets'] = twitter_data | |
except Exception as e: | |
print("Error Getting Twitter Posts", e) | |
return context | |
@register.inclusion_tag('widget/_widget-instagram-posts.html') | |
def get_instagram_posts(posts=1, instagram_user_id): | |
api_url = 'https://api.instagram.com/v1' | |
context = {} | |
try: | |
data_url = '{0}/users/{1}/media/recent/?access_token={2}&count={3}'.format( | |
api_url, | |
instagram_user_id, | |
settings.INSTAGRAM_ACCESS_TOKEN, | |
posts, | |
) | |
query = json.loads( | |
urllib.request.urlopen(data_url).read().decode('utf8')) | |
data = query['data'] | |
for post in data: | |
post['created_time'] = datetime.fromtimestamp( | |
int(post['created_time'])) | |
context['posts'] = data | |
except Exception as e: | |
print("Error Getting Instagram Posts", e) | |
return context | |
@register.inclusion_tag('widget/_widget-youtube-videos.html') | |
def get_youtube_videos(count=1, username): | |
api_url = 'https://www.googleapis.com/youtube/v3/' | |
context = {} | |
try: | |
channels_params = urllib.parse.urlencode(( | |
('part', 'snippet,id'), | |
('forUsername', username), | |
('key', settings.YOUTUBE_API_KEY), | |
)) | |
channel_endpoint = '{0}channels?{1}'.format(api_url, channels_params) | |
channel_query = json.loads( | |
urllib.request.urlopen(channel_endpoint).read().decode('utf8')) | |
if len(channel_query.get('items', [])) > 0: | |
channel_id = channel_query.get('items')[0].get('id') | |
context['channel'] = channel_query.get('items')[0] | |
uploads_params = urllib.parse.urlencode(( | |
('key', settings.YOUTUBE_API_KEY), | |
('channelId', channel_id), | |
('part', 'snippet,id'), | |
('order', 'date'), | |
('maxResults', count), | |
)) | |
uploads_endpoint = '{0}search?{1}'.format(api_url, uploads_params) | |
videos_query = json.loads( | |
urllib.request.urlopen(uploads_endpoint).read().decode('utf8')) | |
for vid in videos_query.get('items', []): | |
vid['snippet']['publishedAt'] = datetime.strptime( | |
vid['snippet']['publishedAt'], '%Y-%m-%dT%H:%M:%S.%fZ') # ISO 8601 | |
context['videos'] = videos_query.get('items', []) | |
except Exception as e: | |
print("Error Getting Youtube Videos", e) | |
return context |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment