def client_factory(args): """ create a connection """ global _CLIENT if not _CLIENT: config = { 'validate_requests': False, 'validate_responses': False } http_client = RequestsClient() hostname = urlparse(args.dos_server).hostname if args.api_key: http_client.set_api_key(hostname, args.api_key, param_name=args.api_key_name, param_in='header') if args.user_pass: (user, passwd) = args.user_pass.split(':') http_client.set_basic_auth(hostname, user, passwd) local_client = Client(args.dos_server, config=config, http_client=http_client) class C(object): def __init__(self, local_client): self.client = local_client.client self.models = local_client.models _CLIENT = C(local_client) return _CLIENT
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
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'))
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() # type: IncomingResponse 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(b"unit:peekaboo").decode('utf-8'), httpretty.last_request().headers.get('Authorization'))
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)
class CallfireClient: 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) def __getattr__(self, item): return getattr(self.swagger_client, item) @staticmethod def swagger_url(): return 'https://www.callfire.com/v2/api-docs/swagger.json'
def lambda_handler(event, context): logger.debug("Event: \n%s", json.dumps(event)) bot = telegram.Bot(token=BOT_TOKEN) update_json = json.loads(event["body"]) update = telegram.Update.de_json(update_json, bot) message = update.message chat = message.chat user = message.from_user text = message.text if user.id != TELEGRAM_USER_ID: bot.sendMessage( chat_id=chat.id, text= "This is a private bot, sorry. If you want a similar bot, check documentation at website https://odoo-sync.sh" ) return RESPONSE_200 openapi_url = urlparse.urlparse(ODOO_OPENAPI_SPECIFICATION_URL) host = openapi_url.hostname db = urlparse.parse_qs(openapi_url.query)['db'][0] http_client = RequestsClient() http_client.set_basic_auth(host, db, ODOO_OPENAPI_TOKEN) odoo = SwaggerClient.from_url( ODOO_OPENAPI_SPECIFICATION_URL, http_client=http_client, ) res = odoo.note_note.addNoteNote(body={'memo': text}).response().result note_id = res['id'] note_url = '/'.join(ODOO_OPENAPI_SPECIFICATION_URL.split('/')[:3]) note_url = '%s/web#id=%s&view_type=form&model=note.note' % (note_url, note_id) bot.sendMessage(chat_id=chat.id, text="Note is created: %s" % note_url, reply_to_message_id=message.message_id) return RESPONSE_200
def get_api_client(config, validation=False): if config.has_key('client'): return config['client'] raw_spec = json.load(open(SPEC_PATH)) raw_spec['host'] = config['nsxManager']['ip'] http_client = RequestsClient() http_client.session.verify = False http_client.set_basic_auth(config['nsxManager']['ip'], config['nsxManager']['user'], 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
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)
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)
from bravado.requests_client import RequestsClient from bravado.client import SwaggerClient from bravado.exception import HTTPNotFound from urllib.parse import urlparse import time import os import os.path import sys nomad_url = 'https://labdev-nomad.esc.rzg.mpg.de/fairdi/nomad/latest/api' user = os.environ['nomad_user'] password = os.environ['nomad_pw'] host = urlparse(nomad_url).netloc.split(':')[0] http_client = RequestsClient() http_client.set_basic_auth(host, user, password) # client = SwaggerClient.from_url('%s/swagger.json' % nomad_url, http_client=http_client) client = SwaggerClient.from_url('%s/swagger.json' % nomad_url) # Searching for data result = client.repo.search(paths='AcAg').response().result if result.pagination.total == 0: print('not found') elif result.pagination.total > 1: print( 'my ids are not specific enough, bummer ... or did I uploaded stuff multiple times?' ) calc = result.results[0] print(calc)
def _prepareBravadoClient(self) -> None: """ Get a Bravado client to the microservice. :return: bravado client. """ swaggerFileLocation = os.path.dirname( os.path.abspath(__file__)) + '/swydo_api.yml' httpClient = RequestsClient() httpClient.set_basic_auth('api.swydo.com', 'API', self._apiKey) swaggerValidation = bool(__debug__) if not self._bravadoClient: logging.info('Getting OpenAPI definition from %s', swaggerFileLocation) try: self._bravadoClient = \ SwaggerClient.from_url( 'file://%s' % swaggerFileLocation, http_client=httpClient, config={ # === bravado config === # Determines what is returned by the service call. 'also_return_response': False, # === bravado-core config ==== # On the client side, validate incoming responses # On the server side, validate outgoing responses 'validate_responses': swaggerValidation, # On the client side, validate outgoing requests # On the server side, validate incoming requests 'validate_requests': swaggerValidation, # Use swagger_spec_validator to validate the swagger spec 'validate_swagger_spec': swaggerValidation, # Use Python classes (models) instead of dicts for #/definitions/{models} # On the client side, this applies to incoming responses. # On the server side, this applies to incoming requests. # # NOTE: outgoing requests on the client side and outgoing responses on the # server side can use either models or dicts. 'use_models': False, # List of user-defined formats of type # :class:`bravado_core.formatter.SwaggerFormat`. These formats are in # addition to the formats already supported by the OpenAPI 2.0 # Specification. 'formats': [], # Fill with None all the missing properties during object unmarshal-ing 'include_missing_properties': False, } ) logging.info('Got OpenAPI spec successfully.') # _client.swagger_spec.api_url = 'http://%s:%s/beep' % config.microservices.beepEndpoint # self._bravadoClient.swagger_spec.api_url = '' % config.microservices.beepURL except Exception: self._bravadoClient = None logging.exception('Cannot find OpenAPI spec.') raise
# https://github.com/Yelp/bravado from bravado.requests_client import RequestsClient from bravado.client import SwaggerClient admin_user_openapi_token = "4b0e734e-6404-4db1-9940-8e7937ca46bc" integration_api_token = "b176ab24-153e-4e7d-8ea1-a77784687102" integration_spec_url = "http://demo.local.com/api/v1/demo_api_de_v1/swagger.json?token=b176ab24-153e-4e7d-8ea1-a77784687102&db=aiat" http_client = RequestsClient() http_client.set_basic_auth('demo.local.com', 'aiat', admin_user_openapi_token) odoo = SwaggerClient.from_url(integration_spec_url, http_client=http_client) result = odoo.res_partner.callMethodForResPartnerModel( method_name="search", body={ 'args': [[('email', '=', '*****@*****.**')]] }).response().incoming_response.json() partner_id = result and result[0] if not partner_id: result = odoo.res_partner.addResPartner(body={ "name": "OpenAPI Support", "email": "*****@*****.**" }).response().result partner_id = result.id odoo.res_partner.callMethodForResPartnerSingleRecord( id=partner_id, method_name="message_post",