Esempio n. 1
0
def get_api_client(config, validation=False):
    if config.has_key('client'):
        return config['client']

    url = "https://%s/api/v1/spec/openapi/nsx_api.json" % config['nsxManager'][
        'ip']
    base64string = base64.encodestring(
        ('%s:%s' % (config['nsxManager']['username'],
                    config['nsxManager']['password'])).encode("utf-8"))[:-1]
    headers = {"Authorization": "Basic %s" % base64string.decode("utf-8")}
    context = ssl.create_default_context()
    context.check_hostname = False
    context.verify_mode = ssl.CERT_NONE
    req = urllib2.Request(url=url, headers=headers)
    response = urllib2.urlopen(req, context=context)
    raw_spec = json.loads(response.read())
    raw_spec['host'] = config['nsxManager']['ip']
    http_client = RequestsClient()
    http_client.session.verify = False
    http_client.set_basic_auth(config['nsxManager']['ip'],
                               config['nsxManager']['username'],
                               config['nsxManager']['password'])
    config = {
        'also_return_response': True,
        'validate_swagger_spec': validation,
        'validate_responses': False,
        'validate_requests': False,
        'use_models': False
    }
    client = SwaggerClient.from_spec(raw_spec,
                                     http_client=http_client,
                                     config=config)
    config['client'] = client
    return client
Esempio n. 2
0
def bitmex(test=True, config=None, api_key=None, api_secret=None):
    # config options at http://bravado.readthedocs.io/en/latest/configuration.html
    if not config:
        config = {
            # Don't use models (Python classes) instead of dicts for #/definitions/{models}
            'use_models': False,
            # bravado has some issues with nullable fields
            'validate_responses': False,
            # Returns response in 2-tuple of (body, response); if False, will only return body
            'also_return_response': True,

            # 'validate_swagger_spec': True,
            # 'validate_requests': True,
            # 'formats': [],
        }

    host = 'https://www.bitmex.com'
    if test:
        host = 'https://testnet.bitmex.com'

    spec_uri = host + '/api/explorer/swagger.json'
    spec_dict = get_swagger_json(spec_uri, exclude_formats=EXCLUDE_SWG_FORMATS)

    if api_key and api_secret:
        request_client = RequestsClient()
        request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret)
        return SwaggerClient.from_spec(spec_dict, origin_url=spec_uri, http_client=request_client, config=config)
    else:
        return SwaggerClient.from_spec(spec_dict, origin_url=spec_uri, http_client=None, config=config)
Esempio n. 3
0
def bitmex(test=True, config=None, api_key=None, api_secret=None):

    if config is None:
        # See full config options at http://bravado.readthedocs.io/en/latest/configuration.html
        config = {
            # Don't use models (Python classes) instead of dicts for #/definitions/{models}
            'use_models': False,
            # bravado has some issues with nullable fields
            'validate_responses': False,
            # Returns response in 2-tuple of (body, response); if False, will only return body
            'also_return_response': True,
        }

    if test:
        host = 'https://testnet.bitmex.com'
    else:
        host = 'https://www.bitmex.com'

    spec_uri = host + '/api/explorer/swagger.json'

    api_key = api_key
    api_secret = api_secret

    if api_key and api_secret:
        request_client = RequestsClient()
        request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret)

        return SwaggerClient.from_url(spec_uri, config=config, http_client=request_client)

    else:
        return SwaggerClient.from_url(spec_uri, config=config)
Esempio n. 4
0
    def __init__(self,
                 access_key: str = None,
                 secret_key: str = None,
                 **kwargs):

        arg_config = kwargs.get("config")
        arg_spec_uri = kwargs.get("spec_uri")
        config = {
            "also_return_response": False,
            "validate_responses": False,
            "use_models": False,
            "host": HOST
        } if not arg_config else arg_config
        spec_uri = SPEC_URI if not arg_spec_uri else arg_spec_uri

        if access_key and secret_key:

            request_client = RequestsClient()
            request_client.authenticator = APIKeyAuthenticator(
                host=config["host"],
                access_key=access_key,
                secret_key=secret_key)

            self.__client = SwaggerClient.from_url(spec_url=spec_uri,
                                                   http_client=request_client,
                                                   config=config)

        else:

            self.__client = SwaggerClient.from_url(spec_url=spec_uri,
                                                   config=config)
Esempio n. 5
0
def bybit(test=True, config=None, api_key=None, api_secret=None):
    host = TESTNET if test else MAINNET

    config = {
        # Don't use models (Python classes) instead of dicts for #/definitions/{models}
        'use_models': False,
        # bravado has some issues with nullable fields
        'validate_responses': False,
        # Returns response in 2-tuple of (body, response); if False, will only return body
        'also_return_response': True,
        'host': host
    } if not config else config

    spec_uri = urljoin(host, "/doc/swagger/v_0_2_10.txt")

    if api_key and api_secret:
        request_client = RequestsClient()
        request_client.authenticator = APIKeyAuthenticator(
            host, api_key, api_secret)

        return SwaggerClient.from_url(spec_uri,
                                      config=config,
                                      http_client=request_client)

    else:

        return SwaggerClient.from_url(spec_uri, config=config)
Esempio n. 6
0
def bybit(test=True, config=None, api_key=None, api_secret=None):
    if test:
        host = 'https://api-testnet.bybit.com'
    else:
        host = 'https://api.bybit.com'

    if config is None:
        # See full config options at http://bravado.readthedocs.io/en/latest/configuration.html
        config = {
            # Don't use models (Python classes) instead of dicts for #/definitions/{models}
            'use_models': False,
            # bravado has some issues with nullable fields
            'validate_responses': False,
            # Returns response in 2-tuple of (body, response); if False, will only return body
            'also_return_response': True,
            "host": host
        }

    api_key = api_key
    api_secret = api_secret

    spec_uri = host + "/doc/swagger/v_0_2_6.txt"

    if api_key and api_secret:
        request_client = RequestsClient()
        request_client.authenticator = APIKeyAuthenticator(host, api_key, api_secret)

        return SwaggerClient.from_url(spec_uri, config=config, http_client=request_client)

    else:

        return SwaggerClient.from_url(spec_uri, config=config)
Esempio n. 7
0
    def __init__(self, API_KEY, API_SECRET):
        print("websocket start 1")
        self.initTradeSide = "Buy"
        HOST = "https://www.bitmex.com"
        SPEC_URI = HOST + "/api/explorer/swagger.json"

        config = {
            'use_models': False,
            'validate_responses': False,
            'also_return_response': True,
        }
        bitMEX = SwaggerClient.from_url(SPEC_URI, config=config)
        self.API_KEY = API_KEY
        self.API_SECRET = API_SECRET
        request_client = RequestsClient()
        print("websocket start 2")
        request_client.authenticator = APIKeyAuthenticator(
            HOST, self.API_KEY, self.API_SECRET)
        self.bitMEXAuthenticated = SwaggerClient.from_url(
            SPEC_URI, config=config, http_client=request_client)
        print("websocket end")
        # Basic authenticated call
        print('\n---A basic Position GET:---')
        print(
            'The following call requires an API key. If one is not set, it will throw an Unauthorized error.'
        )
        self.avgPrice = 0
        self.pos = 0
Esempio n. 8
0
    def __init__(self, service_url: str, token: str) -> None:
        """Create a Swagger API client, load the Swagger definition from the provided service url, and set the
        authentication token for the domain name in the url.

        :param service_url: The base URL for the service, e.g. 'https://mon.hausnet.io/api', without a trailing slash.
        :param token:       The access token provided by the HausNet service.
        :raises:            Any exceptions that were raised during the Swagger client initialization, including
                            connection to the service.
        """
        host = urlparse(service_url).hostname
        http_client = RequestsClient()
        http_client.set_api_key(host=host,
                                api_key=f'Token {token}',
                                param_in='header',
                                param_name='Authorization')
        # noinspection PyBroadException
        try:
            self.client = SwaggerClient.from_url(f'{service_url}/swagger.json',
                                                 http_client=http_client)
            log.info(f"Connected to Heartbeat client at: url={service_url}")
        except Exception as e:
            log.exception(
                f"Failed to connect to Heartbeat client: url={service_url}")
            self.client = None
            raise e
Esempio n. 9
0
def bitmex(test=True, config=None, api_key=None, api_secret=None):
    print('test status: %s' % test)
    if config is None:
        # See full config options at http://bravado.readthedocs.io/en/latest/configuration.html
        config = {
            # Don't use models (Python classes) instead of dicts for #/definitions/{models}
            'use_models': False,
            # bravado has some issues with nullable fields
            'validate_responses': False,
            # Returns response in 2-tuple of (body, response); if False, will only return body
            'also_return_response': True,
        }

    if test:
        host = 'https://testnet.bitmex.com'
    else:
        host = 'https://www.bitmex.com'

    spec_uri = host + '/api/explorer/swagger.json'

    api_key = api_key
    api_secret = api_secret

    if api_key and api_secret:
        request_client = RequestsClient()
        request_client.authenticator = APIKeyAuthenticator(
            host, api_key, api_secret)

        return SwaggerClient.from_url(spec_uri,
                                      config=config,
                                      http_client=request_client)

    else:
        return SwaggerClient.from_url(spec_uri, config=config)
Esempio n. 10
0
def invoke(op, *args, **kwargs):
    if op.http_method != 'get':
        clickclick.action('Invoking..')
    request = construct_request(op, {}, **kwargs)
    c = RequestsClient()
    future = c.request(request)
    future.result()
    clickclick.ok()
Esempio n. 11
0
def get_request_client():
    global _request_client
    if not _request_client:
        rc = RequestsClient()
        rc.authenticator = APIKeyAuthenticator(HOST, config.settings.bitmex_api_key,
                                               config.settings.bitmex_secret_key)
        _request_client = SwaggerClient.from_url(SPEC_URI, config=api_config,
                                                     http_client=rc)
    return _request_client
def annotate_scarif_video(uuid, start, end, label, assignmentId):
    """annotates a video in scarif using bravado.
    args:
        uuid: scarif video uuid (string)
        start: start frame (int)
        end: end frame (int)
        label: string
        assignmentId: AMT assignmentId (string)

    return:
        response: response of swagger client
            http://scarif-api.staging.wearkinetic.com/swagger.json

    side effects:
        a new entry is placed in the videoAnnotations table in scarif
    """
    # query to check that we've not already uploaded this annotation
    query = 'SELECT * FROM \"videoAnnotation\" WHERE label ~\'{:s}\''.format(
        assignmentId)
    import pg8000
    from os import environ as env
    conn = pg8000.connect(user=env['SCARIF_USER'],
                          host=env['SCARIF_HOST'],
                          database='scarif',
                          password=env['SCARIF_PASS'])
    cursor = conn.cursor()
    cursor.execute(query)
    response = cursor.fetchone()
    cursor.close()
    conn.close()

    if response != None:
        print('annotation is already present', file=sys.stderr)
        return response[0]

    #EXAMPLE CURL COMMAND
    #curl -X POST "http://scarif-api.wearkinetic.com/v1/annotate/video" -H "accept: application/json" -H "api_key: asdasd" -H "Content-Type: application/json" -d "{ \"end_time\": 0, \"label\": \"string\", \"start_time\": 1, \"target_uuid\": \"b607a3c1-87d1-417d-afa5-972ab2ce694f\"}"
    from bravado.requests_client import RequestsClient
    from bravado.client import SwaggerClient
    import json
    http_client = RequestsClient()
    http_client.set_api_key('scarif-api.wearkinetic.com',
                            'LITERALLY ANY STRING',
                            param_name='api_key',
                            param_in='header')
    client = SwaggerClient.from_url(
        'http://scarif-api.wearkinetic.com/swagger.json',
        http_client=http_client)
    label_aug = json.dumps({'label': label, 'assignmentId': assignmentId})
    ann = client.get_model('Annotation')(label=label_aug,
                                         start_time=start,
                                         end_time=end,
                                         target_uuid=uuid)
    return client.annotations.annotate(type='video', body=ann).result()
Esempio n. 13
0
def get_request_client():
    global _request_client
    if not _request_client:
        rc = RequestsClient()
        rc.authenticator = APIKeyAuthenticator(
            HOST, config.settings.bitmex_api_key,
            config.settings.bitmex_secret_key)
        _request_client = SwaggerClient.from_url(SPEC_URI,
                                                 config=api_config,
                                                 http_client=rc)
    return _request_client
    def __init__(self, login, password, config=None):
        self.config = {'validate_responses': False, 'proxies': {}}
        self.config.update({} if config is None else config)

        log.debug('CallfireClient.config %s', self.config)
        self.http_client = RequestsClient()
        self.http_client.session.proxies.update(self.config['proxies'])
        self.http_client.set_basic_auth('api.callfire.com', login, password)
        self.swagger_client = SwaggerClient.from_url(
            spec_url=self.swagger_url(),
            http_client=self.http_client,
            config=self.config)
Esempio n. 15
0
 def __init__(self, url, jwt=None, config=DEFAULT_CONFIG):
     swagger_path = "{url}/swagger.json".format(url=url.rstrip("/"))
     if jwt:
         http_client = RequestsClient()
         http_client.set_api_key(host=urlparse(url).netloc,
                                 api_key=f"Bearer {jwt}",
                                 param_name="Authorization",
                                 param_in="header")
     else:
         http_client = None
     self.models = SwaggerClient.from_url(swagger_path, config=config)
     self.client = self.models.TaskService
Esempio n. 16
0
def get_client(auth_token=AUTH_TOKEN):
    with open(os.getenv("SWAGGER_SCHEMA", "swagger.yml")) as f:
        spec = yaml.load(f)

    http_client = RequestsClient()
    http_client.set_api_key(
        HOSTNAME, auth_token,
        param_name='X-API-Key', param_in='header'
    )
    _client = SwaggerClient.from_spec(spec, http_client=http_client)
    _client.swagger_spec.api_url = HOST
    return _client
 def __init__(self, api_key=None):
     http_client = RequestsClient()
     if api_key:
         http_client.set_api_key(self.host,
                                 api_key,
                                 param_name='Authorization',
                                 param_in='header')
     # Usually I'll use `from_url` generation, but current version of specification is not valid OpenAPI 2.0
     # self.client = SwaggerClient.from_url(self.swagger_spec, http_client=http_client)
     swagger_spec = json.load(self.swagger_file.open())
     self.client = SwaggerClient.from_spec(swagger_spec,
                                           http_client=http_client)
Esempio n. 18
0
def get_clients():
    HOST = "https://www.bitmex.com"
    SPEC_URI = HOST + "/api/explorer/swagger.json"
    bitMEX = SwaggerClient.from_url(SPEC_URI, config=config)
    API_KEY = 'emjo2LdiVdhwmTqMESEcO9ut'
    API_SECRET = 'DspbFr4sWjnxUPY4L5yDh13b0MZ1oDGs4kr94EcdJcSH2QkR'
    request_client = RequestsClient()
    request_client.authenticator = APIKeyAuthenticator(HOST, API_KEY,
                                                       API_SECRET)
    bitMEXAuthenticated = SwaggerClient.from_url(SPEC_URI,
                                                 config=config,
                                                 http_client=request_client)
    return bitMEX, bitMEXAuthenticated
Esempio n. 19
0
 def __init__(self, apikey=None):
     http_client = None
     if apikey:
         http_client = RequestsClient()
         http_client.set_api_key('www.openml.org',
                                 apikey,
                                 param_name='api_key',
                                 param_in='header')
     file_path = os.path.abspath(__file__)
     src_path = os.path.join(os.path.dirname(file_path), '..')
     api_defs = os.path.join(src_path, 'swagger.yml')
     self.client = SwaggerClient.from_spec(load_file(api_defs),
                                           http_client=http_client)
Esempio n. 20
0
def _init_http_client(service_id=None, opts=None):
    """
    Initialize and configure HTTP requests client for selected service.
    """
    auth_header = {'token': 'Authorization', 'api_key': 'X-API-KEY', None: ''}
    if service_id:
        opts = _get_trs_opts(service_id)

    http_client = RequestsClient()

    http_client.set_api_key(host=opts['host'],
                            api_key=opts['auth'],
                            param_in='header')
    return http_client
    def __init__(self, api_token=None, proxies=None):
        self._proxies = proxies

        # This is not a top-level import because of circular dependencies
        from neptune import __version__
        self.client_lib_version = __version__

        self.credentials = Credentials(api_token)

        ssl_verify = True
        if os.getenv("NEPTUNE_ALLOW_SELF_SIGNED_CERTIFICATE"):
            urllib3.disable_warnings()
            ssl_verify = False

        self._http_client = RequestsClient(ssl_verify=ssl_verify)
        # for session re-creation we need to keep an authenticator-free version of http client
        self._http_client_for_token = RequestsClient(ssl_verify=ssl_verify)

        user_agent = 'neptune-client/{lib_version} ({system}, python {python_version})'.format(
            lib_version=self.client_lib_version,
            system=platform.platform(),
            python_version=platform.python_version())
        self._http_client.session.headers.update({'User-Agent': user_agent})
        self._http_client_for_token.session.headers.update(
            {'User-Agent': user_agent})

        update_session_proxies(self._http_client.session, proxies)
        update_session_proxies(self._http_client_for_token.session, proxies)

        config_api_url = self.credentials.api_url_opt or self.credentials.token_origin_address
        # We don't need to be able to resolve Neptune host if we use proxy
        if proxies is None:
            self._verify_host_resolution(config_api_url,
                                         self.credentials.token_origin_address)

        # this backend client is used only for initial configuration and session re-creation
        backend_client = self._get_swagger_client(
            '{}/api/backend/swagger.json'.format(config_api_url),
            self._http_client_for_token)
        self._client_config = self._create_client_config(
            self.credentials.api_token, backend_client)

        self._verify_version()

        self._set_swagger_clients(self._client_config)

        self.authenticator = self._create_authenticator(
            self.credentials.api_token, ssl_verify, proxies, backend_client)
        self._http_client.authenticator = self.authenticator
Esempio n. 22
0
def load_client(apikey=None):
    host = 'api.mpcontribs.org' if apikey else 'localhost:5000'
    protocol = 'https' if apikey else 'http'
    spec_url = f'{protocol}://{host}/apispec.json'
    http_client = RequestsClient()
    if apikey:
        http_client.set_api_key(
            host, apikey, param_in='header', param_name='x-api-key'
        )
    loader = Loader(http_client)
    spec_dict = loader.load_spec(spec_url)
    spec_dict['host'] = host
    spec_dict['schemes'] = [protocol]
    return SwaggerClient.from_spec(spec_dict, spec_url, http_client,
                                   {'validate_responses': False})
Esempio n. 23
0
def init_http_client(service_id=None, opts=None):
    """
    Initialize and configure HTTP requests client for selected service.
    """
    auth_header = {'token': 'Authorization', 'api_key': 'X-API-KEY'}
    if service_id:
        opts = wes_config[service_id]

    http_client = RequestsClient()

    http_client.set_api_key(host=opts['host'],
                            api_key=opts['auth'],
                            param_name=auth_header[opts['auth_type']],
                            param_in='header')
    return http_client
Esempio n. 24
0
    def test_simple_get(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        client = RequestsClient()
        params = self._default_params()
        params['params'] = {'foo': 'bar'}

        resp = client.request(params).result()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
Esempio n. 25
0
    def test_simple_get(self):
        httpretty.register_uri(httpretty.GET,
                               "http://swagger.py/client-test",
                               body='expected')

        client = RequestsClient()
        params = self._default_params()
        params['params'] = {'foo': 'bar'}

        resp = client.request(params).result()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
Esempio n. 26
0
    def test_unicode_to_utf8_encode_params(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        client = RequestsClient()
        params = self._default_params()
        params['params'] = {'foo': u'酒場'}

        resp = client.request(params).result()  # type: IncomingResponse

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': [u'酒場']},
                         httpretty.last_request().querystring)
Esempio n. 27
0
    def from_spec(cls, spec_dict, origin_url=None, http_client=None,
                  config=None):
        """
        Build a :class:`SwaggerClient` from a Swagger spec in dict form.

        :param spec_dict: a dict with a Swagger spec in json-like form
        :param origin_url: the url used to retrieve the spec_dict
        :type  origin_url: str
        :param config: Configuration dict - see spec.CONFIG_DEFAULTS

        :rtype: :class:`SwaggerClient`
        """
        http_client = http_client or RequestsClient()
        config = config or {}

        # Apply bravado config defaults
        bravado_config = bravado_config_from_config_dict(config)
        # remove bravado configs from config dict
        for key in set(bravado_config._fields).intersection(set(config)):
            del config[key]
        # set bravado config object
        config['bravado'] = bravado_config

        swagger_spec = Spec.from_dict(
            spec_dict, origin_url, http_client, config,
        )
        return cls(swagger_spec, also_return_response=bravado_config.also_return_response)
Esempio n. 28
0
    def __init__(self, swagger_spec: Spec):
        """
        :param swagger_spec: Complete swagger specification for the API to test.
        """
        self.host = "localhost"

        self.swagger_spec = swagger_spec
        self.base_path = swagger_spec.client_spec_dict.get("basePath", "")

        self.swagger_spec.spec_dict['host'] = f'{self.host}:{TEST_PORT}'

        # setting validate requests to false since we only care about
        # responses
        config = {
            "also_return_response": True,
            "use_models": False,
            "validate_requests": False,
            "formats": swagger_spec.config.get("formats", [])
        }
        self.config = config

        # Bravado provides an async client, but it doesnt run on ioloop? from docs:
        # Fido is a simple, asynchronous HTTP client built on top of Crochet and Twisted with an implementation
        # inspired by the book "Twisted Network Programming Essentials". It is intended to be used in environments
        # where there is no event loop, and where you cannot afford to spin up lots of threads (otherwise you
        # could just use a ThreadPoolExecutor).

        self.swagger_client = SwaggerClient.from_spec(
            self.swagger_spec.spec_dict,
            http_client=RequestsClient(),
            config=config)
Esempio n. 29
0
    def setUpClass(cls):
        # start a test server
        print('setting UP!!!!!!!!!!')
        p = subprocess.Popen(['ga4gh_dos_server'],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             shell=False)
        time.sleep(2)
        # print(p.poll(), p.pid)
        cls._server_process = p

        http_client = RequestsClient()
        # http_client.set_basic_auth(
        #   'localhost', 'admin', 'secret')
        # http_client.set_api_key(
        #   'localhost', 'XXX-YYY-ZZZ', param_in='header')
        local_client = Client(SERVER_URL, http_client=http_client)
        client = local_client.client
        models = local_client.models

        # setup logging
        root = logging.getLogger()
        root.setLevel(logging.ERROR)
        logging.captureWarnings(True)
        cls._models = models

        cls._client = client
        cls._local_client = local_client
Esempio n. 30
0
    def from_url(cls,
                 spec_url,
                 http_client=None,
                 request_headers=None,
                 config=None):
        """
        Build a :class:`SwaggerClient` from a url to the Swagger
        specification for a RESTful API.

        :param spec_url: url pointing at the swagger API specification
        :type spec_url: str
        :param http_client: an HTTP client used to perform requests
        :type  http_client: :class:`bravado.http_client.HttpClient`
        :param request_headers: Headers to pass with http requests
        :type  request_headers: dict
        :param config: bravado_core config dict. See
            bravado_core.spec.CONFIG_DEFAULTS
        """
        # TODO: better way to customize the request for api calls, so we don't
        #       have to add new kwargs for everything
        log.debug(u"Loading from %s" % spec_url)
        http_client = http_client or RequestsClient()
        loader = Loader(http_client, request_headers=request_headers)
        spec_dict = loader.load_spec(spec_url)
        return cls.from_spec(spec_dict, spec_url, http_client, config)
Esempio n. 31
0
    def __init__(self, api_address, api_token):
        self.api_address = api_address
        self.api_token = api_token

        self._http_client = RequestsClient()

        self.backend_swagger_client = SwaggerClient.from_url(
            '{}/api/backend/swagger.json'.format(self.api_address),
            config=dict(validate_swagger_spec=False,
                        validate_requests=False,
                        validate_responses=False,
                        formats=[uuid_format]),
            http_client=self._http_client)

        self.leaderboard_swagger_client = SwaggerClient.from_url(
            '{}/api/leaderboard/swagger.json'.format(self.api_address),
            config=dict(validate_swagger_spec=False,
                        validate_requests=False,
                        validate_responses=False,
                        formats=[uuid_format]),
            http_client=self._http_client)

        self.authenticator = NeptuneAuthenticator(
            self.backend_swagger_client.api.exchangeApiToken(
                X_Neptune_Api_Token=api_token).response().result)
        self._http_client.authenticator = self.authenticator
    def __init__(self, api_token=None, proxies=None):
        from neptune import ANONYMOUS, ANONYMOUS_API_TOKEN
        if api_token == ANONYMOUS:
            api_token = ANONYMOUS_API_TOKEN

        self.credentials = Credentials(api_token)

        ssl_verify = True
        if os.getenv("NEPTUNE_ALLOW_SELF_SIGNED_CERTIFICATE"):
            urllib3.disable_warnings()
            ssl_verify = False

        self._http_client = RequestsClient(ssl_verify=ssl_verify)

        update_session_proxies(self._http_client.session, proxies)

        config_api_url = self.credentials.api_url_opt or self.credentials.token_origin_address
        self._verify_host_resolution(config_api_url, self.credentials.token_origin_address)
        backend_client = self._get_swagger_client('{}/api/backend/swagger.json'.format(config_api_url))
        self._client_config = self._create_client_config(self.credentials.api_token, backend_client)

        self._set_swagger_clients(self._client_config, config_api_url, backend_client)

        self.authenticator = self._create_authenticator(self.credentials.api_token, ssl_verify, proxies)
        self._http_client.authenticator = self.authenticator

        # This is not a top-level import because of circular dependencies
        from neptune import __version__
        self.client_lib_version = __version__

        user_agent = 'neptune-client/{lib_version} ({system}, python {python_version})'.format(
            lib_version=self.client_lib_version,
            system=platform.platform(),
            python_version=platform.python_version())
        self._http_client.session.headers.update({'User-Agent': user_agent})
Esempio n. 33
0
    def test_api_key(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        client = RequestsClient()
        client.set_api_key("swagger.py", 'abc123', param_name='test')
        params = self._default_params()
        params['params'] = {'foo': 'bar'}

        resp = client.request(params).result()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar'], 'test': ['abc123']},
                         httpretty.last_request().querystring)
Esempio n. 34
0
    def from_url(cls,
                 spec_url,
                 http_client=None,
                 request_headers=None,
                 config=None):
        """Build a :class:`SwaggerClient` from a url to the Swagger
        specification for a RESTful API.

        :param spec_url: url pointing at the swagger API specification
        :type spec_url: str
        :param http_client: an HTTP client used to perform requests
        :type  http_client: :class:`bravado.http_client.HttpClient`
        :param request_headers: Headers to pass with http requests
        :type  request_headers: dict
        :param config: Config dict for bravado and bravado_core.
            See CONFIG_DEFAULTS in :module:`bravado_core.spec`.
            See CONFIG_DEFAULTS in :module:`bravado.client`.

        :rtype: :class:`bravado_core.spec.Spec`
        """
        log.debug(u"Loading from %s" % spec_url)
        http_client = http_client or RequestsClient()
        loader = Loader(http_client, request_headers=request_headers)
        spec_dict = loader.load_spec(spec_url)

        # RefResolver may have to download additional json files (remote refs)
        # via http. Wrap http_client's request() so that request headers are
        # passed along with the request transparently. Yeah, this is not ideal,
        # but since RefResolver has new found responsibilities, it is
        # functional.
        if request_headers is not None:
            http_client.request = inject_headers_for_remote_refs(
                http_client.request, request_headers)

        return cls.from_spec(spec_dict, spec_url, http_client, config)
Esempio n. 35
0
def load_client(apikey=None):
    host = 'api.mpcontribs.org' if apikey else 'localhost:5000'
    protocol = 'https' if apikey else 'http'
    spec_url = f'{protocol}://{host}/apispec.json'
    http_client = RequestsClient()
    if apikey:
        http_client.set_api_key(host,
                                apikey,
                                param_in='header',
                                param_name='x-api-key')
    loader = Loader(http_client)
    spec_dict = loader.load_spec(spec_url)
    spec_dict['host'] = host
    spec_dict['schemes'] = [protocol]
    return SwaggerClient.from_spec(spec_dict, spec_url, http_client,
                                   {'validate_responses': False})
Esempio n. 36
0
    def test_basic_auth(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        client = RequestsClient()
        client.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        params = self._default_params()
        params['params'] = {'foo': 'bar'}

        resp = client.request(params).result()

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertEqual('Basic %s' % base64.b64encode("unit:peekaboo"),
                         httpretty.last_request().headers.get('Authorization'))
Esempio n. 37
0
def test_separate_params():
    request_params = {
        'url': 'http://foo.com',
        'connect_timeout': 1,
        'timeout': 2
    }
    sanitized, misc = RequestsClient.separate_params(request_params)
    assert sanitized == {'url': 'http://foo.com'}
    assert misc == {'connect_timeout': 1, 'timeout': 2}
Esempio n. 38
0
    def test_auth_leak(self):
        httpretty.register_uri(
            httpretty.GET, "http://hackerz.py",
            body='expected')

        client = RequestsClient()
        client.set_basic_auth("swagger.py", 'unit', 'peekaboo')
        params = self._default_params()
        params['params'] = {'foo': 'bar'}
        params['url'] = 'http://hackerz.py'

        resp = client.request(params).result()  # type: IncomingResponse

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertTrue(
            httpretty.last_request().headers.get('Authorization') is None)
Esempio n. 39
0
    def test_real_post(self):
        httpretty.register_uri(
            httpretty.POST, "http://swagger.py/client-test",
            body='expected', content_type='text/json')

        client = RequestsClient()
        params = self._default_params()
        params['data'] = {'foo': 'bar'}
        params['method'] = 'POST'

        resp = client.request(params).result()  # type: IncomingResponse

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)

        self.assertEqual('application/x-www-form-urlencoded',
                         httpretty.last_request().headers['content-type'])
        self.assertEqual(b"foo=bar",
                         httpretty.last_request().body)
Esempio n. 40
0
    def test_api_key_header_overwrite(self):
        httpretty.register_uri(
            httpretty.GET, "http://swagger.py/client-test",
            body='expected')

        client = RequestsClient()
        client.set_api_key("swagger.py", 'abc123', param_name='Key',
                           param_in='header')
        params = self._default_params()
        params['params'] = {'foo': 'bar'}
        params['headers'] = {'Key': 'def456'}

        resp = client.request(params).result()  # type: IncomingResponse

        self.assertEqual(200, resp.status_code)
        self.assertEqual('expected', resp.text)
        self.assertEqual({'foo': ['bar']},
                         httpretty.last_request().querystring)
        self.assertEqual('def456', httpretty.last_request().headers['Key'])
Esempio n. 41
0
print('\n---A basic Trade GET:---')
pp.pprint(res)
print('\n---Response details:---')
print("Status Code: %d, headers: %s" % (http_response.status_code, http_response.headers))


#
# Authenticated calls
#
# To do authentication, you must generate an API key.
# Do so at https://testnet.bitmex.com/app/apiKeys

API_KEY = '<API_KEY_HERE>'
API_SECRET = '<API_SECRET_HERE>'

request_client = RequestsClient()
request_client.authenticator = APIKeyAuthenticator(HOST, API_KEY, API_SECRET)

bitMEXAuthenticated = SwaggerClient.from_url(
  SPEC_URI,
  config=config,
  http_client=request_client)

# Basic authenticated call
print('\n---A basic Position GET:---')
print('The following call requires an API key. If one is not set, it will throw an Unauthorized error.')
res, http_response = bitMEXAuthenticated.Position.Position_get(filter=json.dumps({'symbol': 'XBTUSD'})).result()
pp.pprint(res)


# Basic order placement
Esempio n. 42
0
from bravado.client import SwaggerClient
from bravado.requests_client import RequestsClient
import json

# appneta login credentials
email = '*****@*****.**'
password = '******'

# appneta PVC shard instance
instance = 'demo'
instance_host = '%s.pathviewcloud.com' % (instance,)

http_client = RequestsClient()
http_client.set_basic_auth(instance_host, email, password)

with open('swagger.json') as f:
    spec = json.load(f)
client = SwaggerClient.from_spec(spec, 'https://%s' % (instance_host,), http_client=http_client)

# per https://demo.pathviewcloud.com/pvc-data/swagger/
print client.organization.all().result()



# note that some client generators can access the .json file directly from a URL
# however, bravado (and perhaps others) enforce presence of info=>title attribute,
# which is not present in AppNeta-hosted swagger.json and has been added to the
# version in this respository

#swagger_spec_url = 'https://%s/pvc-data/swagger.json' % (instance_host,)
#client = SwaggerClient.from_url(swagger_spec_url, http_client=http_client)