Skip to content

Instantly share code, notes, and snippets.

@angysmark
Last active November 10, 2020 14:48
Show Gist options
  • Save angysmark/6875fdac4b2d88c5492464d290996632 to your computer and use it in GitHub Desktop.
Save angysmark/6875fdac4b2d88c5492464d290996632 to your computer and use it in GitHub Desktop.
import requests
import datetime
import json
from django.core.cache import cache
from django.conf import settings
GFYCAT_GET_URL = 'https://api.gfycat.com/v1/gfycats/{}'
GFYCAT_TOKEN_URL = 'https://api.gfycat.com/v1/oauth/token/'
GFYCAT_TOKEN_CACHE_KEY = 'gfycat_token'
def get_gfycat_auth_header():
token = cache.get(GFYCAT_TOKEN_CACHE_KEY)
if not token:
data = {
'client_id': settings.GFYCAT_API_KEY,
'client_secret': settings.GFYCAT_API_SECRET,
'grant_type': 'client_credentials'
}
resp = requests.post(GFYCAT_TOKEN_URL, data=json.dumps(data))
if resp.status_code < 300:
resp_data = resp.json()
token = resp_data['access_token']
cache.set(GFYCAT_TOKEN_CACHE_KEY, token, resp_data['expires_in'])
else:
return None
return {'Authorization': 'Bearer {}'.format(token)}
def get_gfycat_header(has_data=False):
headers = {'Content-Type': 'application/json'} if has_data else {}
headers.update(get_gfycat_auth_header())
return headers
def get_by_id(gfycat_id):
result = requests.get(GFYCAT_GET_URL.format(gfycat_id),
headers=get_gfycat_header(has_data=False)).json().get(
'gfyItem')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment