def __init__(self, creds=elicit_creds.ElicitCreds(), api_url=PRODUCTION_URL, send_opt=dict(verify=True)): print("Initialize Elicit client library for %s options:" % api_url) print(send_opt) if ((not send_opt['verify']) and api_url.startswith("https")): print('WARNING: not checking SSL') dont_check_ssl() self.api_url = api_url self.swagger_url = self.api_url + '/apidocs/v1/swagger.json' self.app = App._create_(self.swagger_url) self.auth = Security(self.app) self.creds = creds # init swagger client self.client = Client( self.auth, send_opt=send_opt ) # HACK to work around self-signed SSL certs used in development if (self.app.root.host != self.api_url): print( 'WARNING: API URL from swagger doesn\'t match this configuration: [%s] vs [%s]' % (self.api_url, self.app.root.host))
def test_verify(self): """ option for send: verify """ client = Client(send_opt=dict(verify=False)) # testing this client with getPetById httpretty.register_uri(httpretty.GET, 'http://petstore.swagger.wordnik.com/api/pet/1', status=200, content_type='application/json', body=json.dumps(pet_Tom)) resp = client.request(app.op['getPetById'](petId=1)) self.assertEqual(resp.status, 200) self.assertTrue(isinstance(resp.data, Model)) self.assertEqual( resp.data, { u'name': 'Tom', u'tags': [{ u'id': 0, u'name': 'available' }, { u'id': 1, u'name': 'sold' }], u'id': 1 })
def post_progress_collection(self, info): ''' Update status of (pipeline, vid, mid, status) to SQLDB Status: start(must be first inserted), fail, succeed example: curl -X POST \ --header 'Content-Type: application/json' \ --header 'Accept: application/json' \ -d '{ "extra_info": "string", "module_name": "string", "status": "start", "video_name": "string" }' 'http://aladdin1.inf.cs.cmu.edu:83/api/progresses/' ''' # app = App.create(url) app = self.logger client = Client() op1 = app.op['post_progress_collection'] req_resp = client.request( op1( payload={ "extra_info": info.get('extra_info'), "module_name": info.get('module_name'), "status": info.get('status'), # start, fail, succeed "video_name": info.get('video_name') })) return req_resp.status == 201 # 500 if failed
def get_progress_collection(self): ''' curl -X GET --header 'Accept: application/json' 'http://aladdin1.inf.cs.cmu.edu:83/api/progresses/' ''' # app = App.create(url) app = self.logger client = Client() resp = client.request(app.op['get_progress_collection']()) return resp
def init(self): self.server = self["server"] self.port = self["port"] self.api = self["api"] openapi_spec = 'http://{}:{}/{}/swagger.json'.format( self.server, str(self.port), self.api) self.app = App._create_(openapi_spec) self.client = Client() StratusClient.init(self)
def __init__(self, url, *auths): app = App._create_(url) auth = Security(app) for t, cred in auths: auth.update_with(t, cred) client = Client(auth) self.app, self.client = app, client self.client._Client__s.hooks['response'] = logHttp
def client(): c = Client() def init_request(self): self.request = functools.partial(self.request, opt={'url_netloc': 'test:8000'}) c.init_request = functools.partial(init_request, c) c.init_request() return c
def __init__( self, api_key: str, swagger_file: str = "http://www.mingweisamuel.com/riotapi-schema/swaggerspec-2.0.yml" ): self.api_key = api_key self.swagger_file = swagger_file self.app = App.create(swagger_file) self.auth = Security(self.app) self.auth.update_with("api_key", api_key) self.client = Client(self.auth)
def __init__(self, settings): self.settings = settings # create a customized primitive factory for int because library # impractically chooses not to set default (b/t int32 vs int64) b/c # the Swagger/OpenAPI spec doesn't # https://github.com/mission-liao/pyswagger/issues/65 int_factory = SwaggerPrimitive() int_factory.register('integer', '', create_int, validate_int) int_factory.register('integer', None, create_int, validate_int) self.app = SwaggerApp.load(os.path.join( os.path.dirname(os.path.realpath(__file__)), 'luis_api-1.0.swagger.json'), prim=int_factory) self.app.prepare() self.client = Client()
def get_swagger(self): """Gets an authenticated Swagger Client.""" swagger_url = self.get_url( 'swagger', replacement_fields={'base_url': self.base_url}) # load Swagger resource file into App object app = App._create_(swagger_url) auth = Security(app) # TODO: this isn't working... # ValueError: Unknown security name: [api_key] auth.update_with('api_key', self.api_token) # init swagger client client = Client(auth) return app, client
def connect(self, token: str) -> None: """ Establish connection for OpenSTF server :param token: stf access token :return: None """ url = self.swagger_uri self.logger.debug(f"Fetch API spec from: {url}") # load Swagger resource file into App object try: self._app = App._create_(url) # pylint: disable-line except (FileNotFoundError, urllib.error.URLError) as error: self.logger.error(error) raise auth = Security(self._app) auth.update_with('accessTokenAuth', f"Bearer {token}") # token # init swagger client self._client = Client(auth) self.logger.info('StfClient library initiated')
def get_method_list(): from pyswagger import SwaggerApp, SwaggerSecurity from pyswagger.contrib.client.requests import Client from pyswagger.utils import jp_compose app = SwaggerApp._create_(swagger_spec) client = Client() methods = list(app.op.keys()) apis = dict() for m in methods: full_method = m.split('!##!') if not full_method[0] in apis: apis[full_method[0]] = set() apis[full_method[0]].add(full_method[1]) return apis
from pyswagger import App, Security from pyswagger.contrib.client.requests import Client from pyswagger.utils import jp_compose # load Swagger resource file into App object app = App._create_('https://canvas.instructure.com/doc/api/courses.json') auth = Security(app) # auth.update_with('api_key', '9371~SNSl0krgbvfe8JYXS5NSKh7FJLcqO8yNmwZOb9ku79YGDmIXLNCjzjiOBGvfFya9') # api key # auth.update_with('petstore_auth', '12334546556521123fsfss') # oauth2 # init swagger client client = Client(auth)
def client_apptoken(app): auth = Security(app) apptoken = AppToken.objects.first() auth.update_with("AppTokenHeader", f"AppToken {apptoken.key}") client = Client(auth) return client
def main(roomId): host = 'https://goldennumber.aiedu.msra.cn/' jsonpath = '/swagger/v1/swagger.json' app = App._create_(host + jsonpath) client = Client() if not roomId: # Input the roomid if there is no roomid in args roomId = input("Input room id: ") try: roomId = int(roomId) except: roomId = 0 print('Parse room id failed, default join in to room 0') userInfoFile = "userinfo.txt" userId = None nickName = None try: # Use an exist player with open(userInfoFile) as f: userId, nickName = f.read().split(',')[:2] print('Use an exist player: ' + nickName + ' Id: ' + userId) except: # Create a new player userResp = client.request(app.op['NewUser']( nickName='AI Player ' + str(random.randint(0, 9999)))) assert userResp.status == 200 user = userResp.data userId = user.userId nickName = user.nickName print('Create a new player: ' + nickName + ' Id: ' + userId) with open(userInfoFile, "w") as f: f.write("%s,%s" % (userId, nickName)) print('Room id: ' + str(roomId)) while True: stateResp = client.request(app.op['State'](uid=userId, roomid=roomId)) assert stateResp.status == 200 state = stateResp.data if state.state == 2: print('The game has finished') break if state.state == 1: print('The game has not started, query again after 1 second') time.sleep(1) continue if state.hasSubmitted: print('Already submitted this round, wait for next round') if state.maxUserCount == 0: time.sleep(state.leftTime + 1) else: # One round can be finished when all players submitted their numbers if the room have set the max count of users, need to check the state every second. time.sleep(1) continue print('\r\nThis is round ' + str(state.finishedRoundCount + 1)) todayGoldenListResp = client.request( app.op['TodayGoldenList'](roomid=roomId)) assert todayGoldenListResp.status == 200 todayGoldenList = todayGoldenListResp.data if len(todayGoldenList.goldenNumberList) != 0: print('Last golden number is: ' + str(todayGoldenList.goldenNumberList[-1])) number1, number2 = GeneratePredictionNumbers( todayGoldenList.goldenNumberList, state.numbers) if (state.numbers == 2): submitRsp = client.request(app.op['Submit'](uid=userId, rid=state.roundId, n1=str(number1), n2=str(number2))) if submitRsp.status == 200: print('You submit numbers: ' + str(number1) + ', ' + str(number2)) else: print('Error: ' + submitRsp.data.message) else: submitRsp = client.request(app.op['Submit'](uid=userId, rid=state.roundId, n1=str(number1))) if submitRsp.status == 200: print('You submit number: ' + str(number1)) else: print('Error: ' + submitRsp.data.message)
def client(): client = Client() return client
def _create_client(self): return Client()
def connect_to_stf(host, token): global app, client app = App._create_('http://%s/api/v1/swagger.json' % host) auth = Security(app) auth.update_with('accessTokenAuth', 'Bearer ' + token) client = Client(auth)
def generate_client(URL, KEY=None): app = App._create_(URL) auth = Security(app) auth.update_with('apiKeyHeader', KEY) # api key client = Client(auth) return app, client
def client_usertoken(app): auth = Security(app) usertoken = UserToken.objects.first() auth.update_with("UserTokenHeader", f"UserToken {usertoken.key}") client = Client(auth) return client
from pyswagger import SwaggerApp from pyswagger.contrib.client.requests import Client from pyswagger.primitives import Model from ..utils import get_test_data_folder import unittest import httpretty import json import pytest import sys app = SwaggerApp._create_( get_test_data_folder(version='1.2', which='model_subtypes')) client = Client() u_mission = dict(id=1, username='******', password='******') uwi_mary = dict(id=2, username='******', password='******', email='*****@*****.**', phone='123') uwi_kevin = dict(id=3, username='******') @pytest.mark.skipif(sys.version_info[:2] >= (3, 3), reason='httpretty corrupt in python3') class ModelInteritanceTestCase(unittest.TestCase): """ test cases for model inheritance """ @httpretty.activate def test_inheritantce_full(self): """ init a Model with every property along the inheritance path.
from pyswagger import App from pyswagger.contrib.client.requests import Client # load Swagger resource file into App object app = App.create( 'https://esi.tech.ccp.is/latest/swagger.json?datasource=tranquility') swaggerclient = Client() response = swaggerclient.request(app.op['post_universe_names'](ids={ ids: [35, 165] })) # auth = Security(app) # auth.update_with('api_key', '12312312312312312313q') # api key # auth.update_with('petstore_auth', '12334546556521123fsfss') # oauth2 # # init swagger client # client = Client(auth) # # a dict is enough for representing a Model in Swagger # pet_Tom=dict(id=1, name='Tom', photoUrls=['http://test']) # # a request to create a new pet # client.request(app.op['addPet'](body=pet_Tom)) # # - access an Operation object via App.op when operationId is defined # # - a request to get the pet back # pet = client.request(app.op['getPetById'](petId=1)).data # assert pet.id == 1 # assert pet.name == 'Tom' # # new ways to get Operation object corresponding to 'getPetById'.
def connect_to_stf(self, host, token): self.app = App._create_('http://%s/api/v1/swagger.json' % host) auth = Security(self.app) auth.update_with('accessTokenAuth', 'Bearer ' + token) self.client = Client(auth)
def main(): gp = goldPoint() # 初始化 swagger 客户端 host = 'https://goldennumber.aiedu.msra.cn/' jsonpath = '/swagger/v1/swagger.json' app = App._create_(host + jsonpath) client = Client() parser = argparse.ArgumentParser() parser.add_argument('--room', type=int, help='Room ID', required=False) args = parser.parse_args() roomId = args.room if roomId is None: # 如果参数中没有给出room ID,则要求输入room ID roomId = input("Input room id: ") try: roomId = int(roomId) except: roomId = 0 print('Parse room id failed, default join in to room 0') userInfoFile = "userinfo.txt" userId = "019" nickName = None try: # 使用已存在的玩家 with open(userInfoFile) as f: nickName, userId, key = f.read().split(',')[:3] print('Use an exist player: ' + nickName + ' Id: ' + userId) except: # 创建一个新的玩家 userResp = client.request(app.op['NewUser'](nickName='019')) assert userResp.status == 200 user = userResp.data userId = user.userId nickName = user.nickName print('Create a new player: ' + nickName + ' Id: ' + userId) with open(userInfoFile, "w") as f: f.write("%s,%s" % (userId, nickName)) print('Room id: ' + str(roomId)) while True: stateResp = client.request(app.op['State'](uid=userId, roomid=roomId)) if stateResp.status != 200: print('Network issue, query again after 1 second') time.sleep(1) continue state = stateResp.data if state.state == 2: print('The game has finished') break if state.state == 1: print('The game has not started, query again after 1 second') time.sleep(1) continue if state.hasSubmitted: print('Already submitted this round, wait for next round') if state.maxUserCount == 0: time.sleep(state.leftTime + 1) else: # 每秒检测一次:当设置了最大用户数量后,当所有用户都已提交信息后,一个回合就应该结束 time.sleep(1) continue print('\r\nThis is round ' + str(state.finishedRoundCount + 1)) todayGoldenListResp = client.request( app.op['TodayGoldenList'](roomid=roomId)) if todayGoldenListResp.status != 200: print('Network issue, query again after 1 second') time.sleep(1) continue todayGoldenList = todayGoldenListResp.data if len(todayGoldenList.goldenNumberList) != 0: print('Last golden number is: ' + str(todayGoldenList.goldenNumberList[-1])) lastRoundResp = client.request(app.op['History'](roomid=roomId, count=1)) if lastRoundResp.status != 200: print('Network issue, query again after 1 second') time.sleep(1) continue lastScore = 0 if len(lastRoundResp.data.rounds) > 0: scoreArray = [ user for user in lastRoundResp.data.rounds[0].userNumbers if user.userId == userId ] if len(scoreArray) == 1: lastScore = scoreArray[0].score print('Last round score: {}'.format(lastScore)) number1, number2 = gp.predict(todayGoldenList.goldenNumberList) # number1, number2 = random.random(), random.random() print(number1, number2) if (state.numbers == 2): submitRsp = client.request(app.op['Submit']( uid=userId, rid=state.roundId, n1=str(number1), n2=str(number2), token=base64.b64encode( hashlib.sha256( (userId + state.roundId + key).encode(encoding='utf-8')).hexdigest().encode( encoding='utf-8')))) if submitRsp.status == 200: print('You submit numbers: ' + str(number1) + ', ' + str(number2)) else: print('Error: ' + submitRsp.data.message) time.sleep(1) else: submitRsp = client.request(app.op['Submit']( uid=userId, rid=state.roundId, n1=str(number1), token=base64.b64encode( hashlib.sha256( (userId + state.roundId + key).encode(encoding='utf-8')).hexdigest().encode( encoding='utf-8')))) if submitRsp.status == 200: print('You submit number: ' + str(number1)) else: print('Error: ' + submitRsp.data.message) time.sleep(1)
def __init__(self, **kwargs): self._logic_modules = dict() self._data = dict() self.client = Client() super().__init__(**kwargs)