Skip to content

Commit

Permalink
Refactor common header constants and custom media type
Browse files Browse the repository at this point in the history
  • Loading branch information
sfdye committed Aug 21, 2018
1 parent ebcd3a5 commit ae5cdb2
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 30 deletions.
4 changes: 3 additions & 1 deletion github/AuthenticatedUser.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
import github.Authorization
import github.Notification

import Consts


class AuthenticatedUser(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -446,7 +448,7 @@ def create_authorization(self, scopes=github.GithubObject.NotSet, note=github.Gi
if client_secret is not github.GithubObject.NotSet:
post_parameters["client_secret"] = client_secret
if onetime_password is not None:
request_header = {'X-GitHub-OTP': onetime_password} # pragma no cover (Should be covered)
request_header = {Consts.headerOTP: onetime_password} # pragma no cover (Should be covered)
else:
request_header = None
headers, data = self._requester.requestJsonAndCheck(
Expand Down
7 changes: 4 additions & 3 deletions github/CommitComment.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,10 @@
################################################################################

import github.GithubObject

import github.NamedUser

import Consts


class CommitComment(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -171,7 +172,7 @@ def get_reactions(self):
self._requester,
self.url + "/reactions",
None,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)

def create_reaction(self, reaction_type):
Expand All @@ -192,7 +193,7 @@ def create_reaction(self, reaction_type):
"POST",
self.url + "/reactions",
input=post_parameters,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)

Expand Down
37 changes: 37 additions & 0 deletions github/Consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,40 @@
# ##############################################################################
RES_ETAG = "etag"
RES_LAST_MODIFIED = "last-modified"

# Inspired by https://github.com/google/go-github

# Headers

headerRateLimit = "x-ratelimit-limit"
headerRateRemaining = "x-ratelimit-remaining"
headerRateReset = "x-ratelimit-reset"
headerOTP = "X-GitHub-OTP"

defaultMediaType = "application/octet-stream"

# Custom media type for preview API

# https://developer.github.com/changes/2014-12-09-new-attributes-for-stars-api/
mediaTypeStarringPreview = "application/vnd.github.v3.star+json"

# https://developer.github.com/changes/2016-02-19-source-import-preview-api/
mediaTypeImportPreview = "application/vnd.github.barred-rock-preview"

# https://developer.github.com/changes/2016-05-12-reactions-api-preview/
mediaTypeReactionsPreview = "application/vnd.github.squirrel-girl-preview"

# https://developer.github.com/changes/2016-09-14-Integrations-Early-Access/
mediaTypeIntegrationPreview = "application/vnd.github.machine-man-preview+json"

# https://developer.github.com/changes/2017-01-05-commit-search-api/
mediaTypeCommitSearchPreview = "application/vnd.github.cloak-preview"

# https://developer.github.com/changes/2017-02-28-user-blocking-apis-and-webhook/
mediaTypeBlockUsersPreview = "application/vnd.github.giant-sentry-fist-preview+json"

# https://developer.github.com/changes/2017-07-17-update-topics-on-repositories/
mediaTypeTopicsPreview = "application/vnd.github.mercy-preview+json"

# https://developer.github.com/changes/2018-02-22-label-description-search-preview/
mediaTypeLabelDescriptionSearchPreview = "application/vnd.github.symmetra-preview+json"
4 changes: 3 additions & 1 deletion github/Installation.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@
import github.Authorization
import github.Notification

INTEGRATION_PREVIEW_HEADERS = {"Accept": "application/vnd.github.machine-man-preview+json"}
import Consts

INTEGRATION_PREVIEW_HEADERS = {"Accept": Consts.mediaTypeIntegrationPreview}


class Installation(github.GithubObject.NonCompletableGithubObject):
Expand Down
6 changes: 4 additions & 2 deletions github/Issue.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@
import github.IssuePullRequest
import github.Reaction

import Consts


class Issue(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -465,7 +467,7 @@ def get_reactions(self):
self._requester,
self.url + "/reactions",
None,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)

def create_reaction(self, reaction_type):
Expand All @@ -485,7 +487,7 @@ def create_reaction(self, reaction_type):
"POST",
self.url + "/reactions",
input=post_parameters,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)

Expand Down
7 changes: 4 additions & 3 deletions github/IssueComment.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,10 @@
################################################################################

import github.GithubObject

import github.NamedUser

import Consts


class IssueComment(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -148,7 +149,7 @@ def get_reactions(self):
self._requester,
self.url + "/reactions",
None,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)

def create_reaction(self, reaction_type):
Expand All @@ -169,7 +170,7 @@ def create_reaction(self, reaction_type):
"POST",
self.url + "/reactions",
input=post_parameters,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)

Expand Down
4 changes: 3 additions & 1 deletion github/Label.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@

import github.GithubObject

import Consts


class Label(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -107,7 +109,7 @@ def edit(self, name, color, description=github.GithubObject.NotSet):
"PATCH",
self.url,
input=post_parameters,
headers={'Accept': 'application/vnd.github.symmetra-preview+json'}
headers={'Accept': Consts.mediaTypeLabelDescriptionSearchPreview}
)
self._useAttributes(data)

Expand Down
6 changes: 4 additions & 2 deletions github/MainClass.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@
import GithubException
import Invitation

import Consts

atLeastPython3 = sys.hexversion >= 0x03000000

DEFAULT_BASE_URL = "https://api.github.com"
Expand Down Expand Up @@ -504,7 +506,7 @@ def search_commits(self, query, sort=github.GithubObject.NotSet, order=github.Gi
"/search/commits",
url_parameters,
headers={
"Accept": "application/vnd.github.cloak-preview"
"Accept": Consts.mediaTypeCommitSearchPreview
}
)

Expand Down Expand Up @@ -721,7 +723,7 @@ def get_access_token(self, installation_id, user_id=None):
url="/installations/{}/access_tokens".format(installation_id),
headers={
"Authorization": "Bearer {}".format(self.create_jwt()),
"Accept": "application/vnd.github.machine-man-preview+json",
"Accept": Consts.mediaTypeIntegrationPreview,
"User-Agent": "PyGithub/Python"
},
body=body
Expand Down
6 changes: 3 additions & 3 deletions github/PullRequestComment.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@
################################################################################

import github.GithubObject

import github.NamedUser

import Consts

class PullRequestComment(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -205,7 +205,7 @@ def get_reactions(self):
self._requester,
self.url + "/reactions",
None,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)

def create_reaction(self, reaction_type):
Expand All @@ -226,7 +226,7 @@ def create_reaction(self, reaction_type):
"POST",
self.url + "/reactions",
input=post_parameters,
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)
return github.Reaction.Reaction(self._requester, headers, data, completed=True)

Expand Down
5 changes: 3 additions & 2 deletions github/Reaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@
################################################################################

import github.GithubObject

import github.NamedUser

import Consts


class Reaction(github.GithubObject.CompletableGithubObject):
"""
Expand Down Expand Up @@ -77,7 +78,7 @@ def delete(self):
self._requester.requestJsonAndCheck(
"DELETE",
self._parentUrl("") + "/reactions/" + str(self.id),
headers={'Accept': 'application/vnd.github.squirrel-girl-preview'}
headers={'Accept': Consts.mediaTypeReactionsPreview}
)

def _initAttributes(self):
Expand Down
14 changes: 8 additions & 6 deletions github/Repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@
import github.StatsPunchCard
import github.Stargazer

import Consts

atLeastPython3 = sys.hexversion >= 0x03000000


Expand Down Expand Up @@ -1077,7 +1079,7 @@ def create_label(self, name, color, description=github.GithubObject.NotSet):
"POST",
self.url + "/labels",
input=post_parameters,
headers={'Accept': 'application/vnd.github.symmetra-preview+json'}
headers={'Accept': Consts.mediaTypeLabelDescriptionSearchPreview}
)
return github.Label.Label(self._requester, headers, data, completed=True)

Expand Down Expand Up @@ -1179,7 +1181,7 @@ def create_source_import(self, vcs, vcs_url, vcs_username=github.GithubObject.No
if vcs_password is not github.GithubObject.NotSet:
put_parameters["vcs_password"] = vcs_password

import_header = {"Accept": "application/vnd.github.barred-rock-preview"}
import_header = {"Accept": Consts.mediaTypeImportPreview}

headers, data = self._requester.requestJsonAndCheck(
"PUT",
Expand Down Expand Up @@ -2165,7 +2167,7 @@ def get_source_import(self):
:calls: `GET /repos/:owner/:repo/import <https://developer.github.com/v3/migration/source_imports/#get-import-progress>`_
:rtype: :class:`github.SourceImport.SourceImport`
"""
import_header = {"Accept": "application/vnd.github.barred-rock-preview"}
import_header = {"Accept": Consts.mediaTypeImportPreview}
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/import",
Expand Down Expand Up @@ -2198,7 +2200,7 @@ def get_stargazers_with_dates(self):
self._requester,
self.url + "/stargazers",
None,
headers={'Accept': 'application/vnd.github.v3.star+json'}
headers={'Accept': Consts.mediaTypeStarringPreview}
)

def get_stats_contributors(self):
Expand Down Expand Up @@ -2366,7 +2368,7 @@ def get_topics(self):
headers, data = self._requester.requestJsonAndCheck(
"GET",
self.url + "/topics",
headers={'Accept': 'application/vnd.github.mercy-preview+json'}
headers={'Accept': Consts.mediaTypeTopicsPreview}
)
return data['names']

Expand Down Expand Up @@ -2473,7 +2475,7 @@ def replace_topics(self, topics):
headers, data = self._requester.requestJsonAndCheck(
"PUT",
self.url + "/topics",
headers={'Accept': 'application/vnd.github.mercy-preview+json'},
headers={'Accept': Consts.mediaTypeTopicsPreview},
input=post_parameters
)

Expand Down
12 changes: 6 additions & 6 deletions github/Requester.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def __customConnection(self, url):
def __createException(self, status, headers, output):
if status == 401 and output.get("message") == "Bad credentials":
cls = GithubException.BadCredentialsException
elif status == 401 and 'x-github-otp' in headers and re.match(r'.*required.*', headers['x-github-otp']):
elif status == 401 and Consts.headerOTP in headers and re.match(r'.*required.*', headers[Consts.headerOTP]):
cls = GithubException.TwoFactorException # pragma no cover (Should be covered)
elif status == 403 and output.get("message").startswith("Missing or invalid User Agent string"):
cls = GithubException.BadUserAgentException
Expand Down Expand Up @@ -340,7 +340,7 @@ def encode(local_path):
mime_type = headers["Content-Type"]
else:
guessed_type = mimetypes.guess_type(input)
mime_type = guessed_type[0] if guessed_type[0] is not None else "application/octet-stream"
mime_type = guessed_type[0] if guessed_type[0] is not None else Consts.defaultMediaType
f = open(local_path, 'rb')
return mime_type, f

Expand Down Expand Up @@ -371,10 +371,10 @@ def __requestEncode(self, cnx, verb, url, parameters, requestHeaders, input, enc

status, responseHeaders, output = self.__requestRaw(cnx, verb, url, requestHeaders, encoded_input)

if "x-ratelimit-remaining" in responseHeaders and "x-ratelimit-limit" in responseHeaders:
self.rate_limiting = (int(responseHeaders["x-ratelimit-remaining"]), int(responseHeaders["x-ratelimit-limit"]))
if "x-ratelimit-reset" in responseHeaders:
self.rate_limiting_resettime = int(responseHeaders["x-ratelimit-reset"])
if Consts.headerRateRemaining in responseHeaders and Consts.headerRateLimit in responseHeaders:
self.rate_limiting = (int(responseHeaders[Consts.headerRateRemaining]), int(responseHeaders[Consts.headerRateLimit]))
if Consts.headerRateReset in responseHeaders:
self.rate_limiting_resettime = int(responseHeaders[Consts.headerRateReset])

if "x-oauth-scopes" in responseHeaders:
self.oauth_scopes = responseHeaders["x-oauth-scopes"].split(", ")
Expand Down

0 comments on commit ae5cdb2

Please sign in to comment.