Skip to content

Instantly share code, notes, and snippets.

@dorokhin
Last active July 15, 2021 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dorokhin/d9f18859c730ea4750e368e84337b0cc to your computer and use it in GitHub Desktop.
Save dorokhin/d9f18859c730ea4750e368e84337b0cc to your computer and use it in GitHub Desktop.
Access GitHub API from python
import requests, json
api_url = 'https://api.github.com'
authorize_url = 'https://github.com/login/oauth/authorize'
token_url = 'https://github.com/login/oauth/access_token'
class GitHub():
def __init__(self, client_id = '', client_secret = '', access_token = ''):
self.client_id = client_id
self.client_secret = client_secret
self.access_token = access_token
def authorization_url(self, scope):
return authorize_url + '?client_id={}&client_secret={}&scope={}'.format(
self.client_id,
self.client_secret,
scope
)
def get_token(self, code):
"""Fetch GitHub Access Token for GitHub OAuth."""
headers = { 'Accept': 'application/json' }
params = {
'code': code,
'client_id': self.client_id,
'client_secret': self.client_secret,
}
data = requests.post(token_url, params=params, headers=headers).json()
return data.get('access_token', None)
def get(self, route_url, params = {}):
url = api_url + route_url
params['access_token'] = self.access_token
return requests.get(url, params=params).json()
def post(self, route_url, params = {}):
url = api_url + route_url
params['access_token'] = self.access_token
return requests.post(url, params=params).json()
def delete(self, route_url, params = {}):
url = api_url + route_url
params['access_token'] = self.access_token
return requests.delete(url, params=params)
@staticmethod
def get_user_from_token(access_token):
"""Fetch user data using the access token."""
url = api_url + '/user'
params = { 'access_token': access_token }
return requests.get(url, params=params).json()
from flask_sqlalchemy import SQLAlchemy
from github import GitHub
db = SQLAlchemy()
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer(), primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
avatar_url = db.Column(db.String(80), nullable=True)
github_id = db.Column(db.Integer(), nullable=True)
def __init__(self, username, avatar_url, github_id):
self.username = username
self.avatar_url = avatar_url
self.github_id = github_id
@staticmethod
def find_or_create_from_token(access_token):
data = GitHub.get_user_from_token(access_token)
"""Find existing user or create new User instance"""
instance = User.query.filter_by(username=data['login']).first()
if not instance:
instance = User(data['login'], data['avatar_url'], data['id'])
db.session.add(instance)
db.session.commit()
return instance
def __repr__(self):
return "<User: {}>".format(self.username)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment