forked from sigmavirus24/github3.py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdecorators.py
More file actions
65 lines (55 loc) · 2 KB
/
Copy pathdecorators.py
File metadata and controls
65 lines (55 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
github3.decorators
==================
This module provides decorators to the rest of the library
"""
from functools import wraps
from requests.models import Response
import os
try: # (No coverage)
# python2
from StringIO import StringIO # (No coverage)
except ImportError: # (No coverage)
# python3
from io import BytesIO as StringIO # NOQA
def requires_auth(func):
"""Decorator to note which object methods require authorization."""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
auth = False
if hasattr(self, '_session'):
auth = (self._session.auth or
self._session.headers.get('Authorization'))
if auth:
return func(self, *args, **kwargs)
else:
from github3.models import GitHubError
# Mock a 401 response
r = Response()
r.status_code = 401
r.encoding = 'utf-8'
r.raw = StringIO('{"message": "Requires authentication"}'.encode())
raise GitHubError(r)
return auth_wrapper
def requires_basic_auth(func):
"""Decorator to note which object methods require username/password
authorization and won't work with token based authorization."""
@wraps(func)
def auth_wrapper(self, *args, **kwargs):
if hasattr(self, '_session') and self._session.auth:
return func(self, *args, **kwargs)
else:
from github3.models import GitHubError
# Mock a 401 response
r = Response()
r.status_code = 401
r.encoding = 'utf-8'
msg = ('{"message": "Requires username/password '
'authentication"}').encode()
r.raw = StringIO(msg)
raise GitHubError(r)
return auth_wrapper
# Use mock decorators when generating documentation, so all functino signatures
# are displayed correctly
if os.environ.get('GENERATING_DOCUMENTATION', None) == 'github3':
requires_auth = requires_basic_auth = lambda x: x