Skip to content
Snippets Groups Projects
Select Git revision
  • a8f2bb70232bd5a8f787770ba9ca0efbed2d0c00
  • master default protected
  • hsh-2025073100
  • hsh-2025012100
  • hsh-2024111900
  • hsh-2024072400
  • hsh-2024060300
  • hsh-2024012900
  • hsh-2023121100
  • hsh-v1.1.9
  • hsh-v1.1.7
11 results

sbcl_version

Blame
  • saltapis.py 2.07 KiB
    from django.conf import settings
    
    import requests
    from getpass import getpass
    
    
    class AbstractApi(object):
        '''
            Defines an abstract api to inherit from.
            You MUST specify a BASE_URL for your api to build a proper request url.
        '''
    
        BASE_URL = ''
    
        def __init__(self, username='', password='', token=''):
            ''' Set a token to work with '''
            if not self.BASE_URL:
                raise NotImplementedError('Please provide an BASE_URL')
    
            if token:
                self.token = token
            else:
                self.token = self.obtain_auth_token(username, password)
    
        def request(self, method='get', resource='/', headers={}, data={}):
            return getattr(requests, method)(
                self.BASE_URL + resource,
                headers=headers,
                data=data
            )
    
        def obtain_auth_token(self, username, password):
            res = self.request('post', '/login', headers={'Accept': 'application/json'}, data={
                'username': username,
                'password': password,
                'eauth': 'pam'
            })
    
            if res.status_code != 200:
                raise Exception('{} - {}'.format(res.status_code, res.text))
    
            return res.json().get('return')[0].get('token')
    
    
    class SaltCherrypy(AbstractApi):
    
        BASE_URL = '{protocol}://{host}:{port}'.format(**settings.SALT_API['cherrypy'])
    
        def logout(self):
            return self.request('post', '/logout', headers={
                'Accept': 'application/json',
                'X-Auth-Token': self.token
            })
    
        def get(self, module, target='*', api_args=[], api_kwargs={}):
            return self.request(
                'post',
                data={
                    'client': 'local',
                    'fun': module,
                    'tgt': target,
                    'arg': api_args,
                    'kwarg': api_kwargs
                },
                headers={
                    'Accept': 'application/json',
                    'X-Auth-Token': self.token
                }
            ).json().get('return')[0]
    
    
    class SaltTornado(AbstractApi):
    
        BASE_URL = '{protocol}://{host}:{port}'.format(**settings.SALT_API['tornado'])