Skip to content

Commit 8c9c02c

Browse files
authored
awxkit: allow to modify api base url (#14835)
Signed-off-by: Julen Landa Alustiza <[email protected]>
1 parent 8a902de commit 8c9c02c

File tree

17 files changed

+54
-49
lines changed

17 files changed

+54
-49
lines changed

awxkit/awxkit/api/client.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,16 @@ def __init__(self, server, verify=False):
4343
self.session = requests.Session()
4444
self.uses_session_cookie = False
4545

46-
def get_session_requirements(self, next='/api/'):
47-
self.get('/api/') # this causes a cookie w/ the CSRF token to be set
46+
def get_session_requirements(self, next=config.api_base_path):
47+
self.get(config.api_base_path) # this causes a cookie w/ the CSRF token to be set
4848
return dict(next=next)
4949

5050
def login(self, username=None, password=None, token=None, **kwargs):
5151
if username and password:
5252
_next = kwargs.get('next')
5353
if _next:
5454
headers = self.session.headers.copy()
55-
response = self.post('/api/login/', headers=headers, data=dict(username=username, password=password, next=_next))
55+
response = self.post(f"{config.api_base_path}login/", headers=headers, data=dict(username=username, password=password, next=_next))
5656
# The login causes a redirect so we need to search the history of the request to find the header
5757
for historical_response in response.history:
5858
if 'X-API-Session-Cookie-Name' in historical_response.headers:

awxkit/awxkit/api/mixins/has_status.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from awxkit.utils import poll_until
55
from awxkit.exceptions import WaitUntilTimeout
6+
from awxkit.config import config
67

78

89
def bytes_to_str(obj):
@@ -83,7 +84,7 @@ def assert_status(self, status_list, msg=None):
8384
if getattr(self, 'job_explanation', '').startswith('Previous Task Failed'):
8485
try:
8586
data = json.loads(self.job_explanation.replace('Previous Task Failed: ', ''))
86-
dependency = self.walk('/api/v2/{0}s/{1}/'.format(data['job_type'], data['job_id']))
87+
dependency = self.walk('/{0}v2/{1}s/{2}/'.format(config.api_base_path, data['job_type'], data['job_id']))
8788
if hasattr(dependency, 'failure_output_details'):
8889
msg += '\nDependency output:\n{}'.format(dependency.failure_output_details())
8990
else:

awxkit/awxkit/api/pages/base.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -150,19 +150,21 @@ def get_oauth2_token(self, username='', password='', client_id=None, description
150150
HTTPBasicAuth(client_id, client_secret)(req)
151151
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
152152
resp = self.connection.post(
153-
'/api/o/token/', data={"grant_type": "password", "username": username, "password": password, "scope": scope}, headers=req.headers
153+
f"{config.api_base_path}o/token/",
154+
data={"grant_type": "password", "username": username, "password": password, "scope": scope},
155+
headers=req.headers,
154156
)
155157
elif client_id:
156158
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
157159
resp = self.connection.post(
158-
'/api/o/token/',
160+
f"{config.api_base_path}o/token/",
159161
data={"grant_type": "password", "username": username, "password": password, "client_id": client_id, "scope": scope},
160162
headers=req.headers,
161163
)
162164
else:
163165
HTTPBasicAuth(username, password)(req)
164166
resp = self.connection.post(
165-
'/api/v2/users/{}/personal_tokens/'.format(username),
167+
'{0}v2/users/{1}/personal_tokens/'.format(config.api_base_path, username),
166168
json={"description": description, "application": None, "scope": scope},
167169
headers=req.headers,
168170
)
@@ -207,7 +209,7 @@ def _cleanup(self, delete_method):
207209
jobs = []
208210
for active_job in active_jobs:
209211
job_type = active_job['type']
210-
endpoint = '/api/v2/{}s/{}/'.format(job_type, active_job['id'])
212+
endpoint = '{}v2/{}s/{}/'.format(config.api_base_path, job_type, active_job['id'])
211213
job = self.walk(endpoint)
212214
jobs.append(job)
213215
job.cancel()

awxkit/awxkit/api/resources.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from awxkit.config import config
2+
3+
14
class Resources(object):
25
_activity = r'activity_stream/\d+/'
36
_activity_stream = 'activity_stream/'
@@ -285,6 +288,9 @@ class Resources(object):
285288
common = api + r'v\d+/'
286289
v2 = api + 'v2/'
287290

291+
def __init__(self, api):
292+
self.api = api
293+
288294
def __getattr__(self, resource):
289295
if resource[:3] == '___':
290296
raise AttributeError('No existing resource: {}'.format(resource))
@@ -299,4 +305,4 @@ def __getattr__(self, resource):
299305
return '{0}{1}'.format(getattr(self, prefix), getattr(self, resource))
300306

301307

302-
resources = Resources()
308+
resources = Resources(api=config.api_base_path)

awxkit/awxkit/awx/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -122,5 +122,5 @@ def as_user(v, username, password=None):
122122

123123

124124
def uses_sessions(connection):
125-
session_login = connection.get('/api/login/')
125+
session_login = connection.get(f"{config.api_base_path}login/")
126126
return session_login.status_code == 200

awxkit/awxkit/cli/custom.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from .stdout import monitor, monitor_workflow
55
from .utils import CustomRegistryMeta, color_enabled
66
from awxkit import api
7+
from awxkit.config import config
78
from awxkit.exceptions import NoContent
89

910

@@ -479,7 +480,7 @@ def perform(self, **kwargs):
479480
options = ', '.join(RoleMixin.roles[flag])
480481
raise ValueError("invalid choice: '{}' must be one of {}".format(role, options))
481482
value = kwargs[flag]
482-
target = '/api/v2/{}/{}'.format(resource, value)
483+
target = '{}v2/{}/{}'.format(config.api_base_path, resource, value)
483484
detail = self.page.__class__(target, self.page.connection).get()
484485
object_roles = detail['summary_fields']['object_roles']
485486
actual_role = object_roles[role + '_role']

awxkit/awxkit/cli/stdout.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import time
77

88
from .utils import cprint, color_enabled, STATUS_COLORS
9+
from awxkit.config import config
910
from awxkit.utils import to_str
1011

1112

@@ -17,7 +18,7 @@ def monitor_workflow(response, session, print_stdout=True, action_timeout=None,
1718
}
1819

1920
def fetch(seen):
20-
results = response.connection.get('/api/v2/unified_jobs', payload).json()['results']
21+
results = response.connection.get(f"{config.api_base_path}v2/unified_jobs", payload).json()['results']
2122

2223
# erase lines we've previously printed
2324
if print_stdout and sys.stdout.isatty():

awxkit/awxkit/config.py

+1
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,4 @@ def getvalue(self, name):
3232
config.client_connection_attempts = int(os.getenv('AWXKIT_CLIENT_CONNECTION_ATTEMPTS', 5))
3333
config.prevent_teardown = to_bool(os.getenv('AWXKIT_PREVENT_TEARDOWN', False))
3434
config.use_sessions = to_bool(os.getenv('AWXKIT_SESSIONS', False))
35+
config.api_base_path = os.getenv('AWXKIT_API_BASE_PATH', '/api/')

awxkit/awxkit/utils/__init__.py

-2
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,8 @@
1414
from awxkit.words import words
1515
from awxkit.exceptions import WaitUntilTimeout
1616

17-
1817
log = logging.getLogger(__name__)
1918

20-
2119
cloud_types = (
2220
'aws',
2321
'azure',

docs/docsite/conf.py

+9-5
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616

1717
# The name for this set of Sphinx documents. If None, it defaults to
1818
# "<project> v<release> documentation".
19-
#html_title = None
19+
# html_title = None
2020
html_title = 'Ansible AWX community documentation'
2121

2222
# A shorter title for the navigation bar. Default is the same as html_title.
23-
#html_short_title = None
23+
# html_short_title = None
2424
html_short_title = 'AWX community documentation'
2525

2626
htmlhelp_basename = 'AWX_docs'
@@ -54,8 +54,8 @@
5454

5555
language = 'en'
5656

57-
locale_dirs = ['locale/'] # path is example but recommended.
58-
gettext_compact = False # optional.
57+
locale_dirs = ['locale/'] # path is example but recommended.
58+
gettext_compact = False # optional.
5959

6060
rst_epilog = """
6161
.. |atqi| replace:: *AWX Quick Installation Guide*
@@ -88,4 +88,8 @@
8888
.. |rhaap| replace:: Red Hat Ansible Automation Platform
8989
.. |RHAT| replace:: Red Hat Ansible Automation Platform controller
9090
91-
""" % (version, pubdateshort, pubdate)
91+
""" % (
92+
version,
93+
pubdateshort,
94+
pubdate,
95+
)

docs/docsite/rst/rest_api/_swagger/swagger.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -35,12 +35,8 @@ def assets(app, exception):
3535
_, extension = os.path.splitext(asset)
3636
if extension in ('py', 'pyc'):
3737
continue
38-
if not exception and os.path.exists(
39-
os.path.join(app.outdir, '_static')
40-
):
41-
copyfile(
42-
os.path.join(here, asset),
43-
os.path.join(app.outdir, '_static', asset))
38+
if not exception and os.path.exists(os.path.join(app.outdir, '_static')):
39+
copyfile(os.path.join(here, asset), os.path.join(app.outdir, '_static', asset))
4440

4541

4642
def setup(app):

manage.py

+1
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,5 @@
55

66
if __name__ == '__main__':
77
from awx import manage
8+
89
manage()

tools/data_generators/rbac_dummy_data_generator.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
WorkflowJobTemplateNode,
5454
batch_role_ancestor_rebuilding,
5555
)
56-
from awx.main.models.schedules import Schedule #noqa
56+
from awx.main.models.schedules import Schedule # noqa
5757

5858
from awx.main.signals import disable_activity_stream, disable_computed_fields # noqa
5959

@@ -595,8 +595,6 @@ def make_the_data():
595595
schedule._is_new = _
596596
schedules.append(schedule)
597597

598-
599-
600598
print('# Creating %d Labels' % n_labels)
601599
org_idx = 0
602600
for n in spread(n_labels, n_organizations):

tools/scripts/compilemessages.py

+15-14
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,12 @@ def popen_wrapper(args, os_err_exc_type=Exception, stdout_encoding='utf-8'):
4040
p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt')
4141
except OSError as e:
4242
strerror = force_text(e.strerror, DEFAULT_LOCALE_ENCODING, strings_only=True)
43-
raise Exception(os_err_exc_type, os_err_exc_type('Error executing %s: %s' %
44-
(args[0], strerror)), sys.exc_info()[2])
43+
raise Exception(os_err_exc_type, os_err_exc_type('Error executing %s: %s' % (args[0], strerror)), sys.exc_info()[2])
4544
output, errors = p.communicate()
4645
return (
4746
force_text(output, stdout_encoding, strings_only=True, errors='strict'),
4847
force_text(errors, DEFAULT_LOCALE_ENCODING, strings_only=True, errors='replace'),
49-
p.returncode
48+
p.returncode,
5049
)
5150

5251

@@ -65,7 +64,13 @@ def get_system_encoding():
6564

6665

6766
_PROTECTED_TYPES = (
68-
type(None), int, float, Decimal, datetime.datetime, datetime.date, datetime.time,
67+
type(None),
68+
int,
69+
float,
70+
Decimal,
71+
datetime.datetime,
72+
datetime.date,
73+
datetime.time,
6974
)
7075

7176

@@ -111,8 +116,7 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
111116
# working unicode method. Try to handle this without raising a
112117
# further exception by individually forcing the exception args
113118
# to unicode.
114-
s = ' '.join(force_text(arg, encoding, strings_only, errors)
115-
for arg in s)
119+
s = ' '.join(force_text(arg, encoding, strings_only, errors) for arg in s)
116120
return s
117121

118122

@@ -140,17 +144,14 @@ def force_text(s, encoding='utf-8', strings_only=False, errors='strict'):
140144
print('processing file %s in %s\n' % (f, dirpath))
141145
po_path = os.path.join(dirpath, f)
142146
if has_bom(po_path):
143-
raise Exception("The %s file has a BOM (Byte Order Mark). "
144-
"Django only supports .po files encoded in "
145-
"UTF-8 and without any BOM." % po_path)
147+
raise Exception(
148+
"The %s file has a BOM (Byte Order Mark). " "Django only supports .po files encoded in " "UTF-8 and without any BOM." % po_path
149+
)
146150
base_path = os.path.splitext(po_path)[0]
147151
# Check writability on first location
148152
if i == 0 and not is_writable((base_path + '.mo')):
149-
raise Exception("The po files under %s are in a seemingly not writable location. "
150-
"mo files will not be updated/created." % dirpath)
151-
args = [program] + program_options + [
152-
'-o', (base_path + '.mo'), (base_path + '.po')
153-
]
153+
raise Exception("The po files under %s are in a seemingly not writable location. " "mo files will not be updated/created." % dirpath)
154+
args = [program] + program_options + ['-o', (base_path + '.mo'), (base_path + '.po')]
154155
output, errors, status = popen_wrapper(args)
155156
if status:
156157
if errors:

tools/scripts/firehose.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ class YieldedRows(StringIO):
6666
def __init__(self, job_id, rows, created_stamp, modified_stamp, *args, **kwargs):
6767
self.rows = rows
6868
self.rowlist = []
69-
for (event, module) in itertools.product(EVENT_OPTIONS, MODULE_OPTIONS):
69+
for event, module in itertools.product(EVENT_OPTIONS, MODULE_OPTIONS):
7070
event_data_json = {"task_action": module, "name": "Do a {} thing".format(module), "task": "Do a {} thing".format(module)}
7171
row = (
7272
"\t".join(

tools/scripts/list_fields.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,11 @@ def _get_class_full_name(cls_):
66

77

88
class _ModelFieldRow(object):
9-
109
def __init__(self, field):
1110
self.field = field
1211
self.name = field.name
1312
self.type_ = _get_class_full_name(type(field))
14-
if self.field.many_to_many\
15-
or self.field.many_to_one\
16-
or self.field.one_to_many\
17-
or self.field.one_to_one:
13+
if self.field.many_to_many or self.field.many_to_one or self.field.one_to_many or self.field.one_to_one:
1814
self.related_model = _get_class_full_name(self.field.remote_field.model)
1915
else:
2016
self.related_model = 'N/A'

tools/sosreport/controller.py

-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ class Controller(Plugin, RedHatPlugin):
6666
short_desc = "Ansible Automation Platform controller information"
6767

6868
def setup(self):
69-
7069
for path in SOSREPORT_CONTROLLER_DIRS:
7170
self.add_copy_spec(path)
7271

0 commit comments

Comments
 (0)