def test__get_car_data__returns_formatted_json(): subject = Api(fake_car_list) actual = subject.get_car_data() expected = { "manufacturers": [{ "name": "Honda", "carModels": [{ "name": "Civic", "carClass": "HS" }, { "name": "Accord", "carClass": "GS" }] }, { "name": "Subaru", "carModels": [{ "name": "BRZ", "carClass": "DS" }, { "name": "WRX", "carClass": "DS" }] }] } assert actual == expected
def register(self, api: Api): """ Register api webhook(depends on api realization) :param api: Api instance :return: """ api.register(self.get_app())
def __init__(self): __host = getConfPart("db", "host") __user = getConfPart("db", "user") __password = getConfPart("db", "password") __dbName = getConfPart("db", "dbName") self.api = Api(__host, __user, __password, __dbName) self.userId = None
def create_user(user): response = Api().post(Api.USERS_URL, json=user.json_user()) assert response.status_code == 201 response_data = response.json() user.id = response_data['id'] print(f'--> user created, id:{user.id}') return user, response_data
def __record_button_pressed(self): if self.__isRecording: self.__isRecording = False self.__app.setButtonImage(self.__RECORD_BUTTON_NAME, "src/gui/gfx/button_record_start.gif") Api.stop_recording() else: self.__isRecording = True self.__app.setButtonImage(self.__RECORD_BUTTON_NAME, "src/gui/gfx/button_record_stop.gif") Api.start_recording()
def api_is_up(context): domain = Api().domain port = Api().port from requests import get status_request = str( get(f"http://{domain}:{port}/api/v1/").text.encode('utf-8')).lower() assert all([ bool(txt) for txt in ['api', 'is', 'online'] if txt in str(status_request) ]), f"The api is not up"
def __init__(self): self.__tempdir = TemporaryDirectory() config.current = {'storage': {'dbPath': self.__tempdir.name}} cherrypy.config['tools.json_out.handler'] = src.core.tools.json_handler cherrypy.config.update({'environment': "test_suite"}) # prevent the HTTP server from ever starting cherrypy.server.unsubscribe() api = Api() cherrypy.tree.mount(api, '/api', api.config()) cherrypy.engine.start()
def __init__(self, *args, **kwargs): super(QFrame, self).__init__(*args, **kwargs) account_api = Api("/account") status, res = account_api.get() if status == 200: self.credits = "{:.2f}".format(round(res['customer']['credits'], 3)) self.head_img = None self.menu_button = None self.credits = 15 self._init_ui() self.setStyleSheet(app_style)
def on_logout_clicked(self): with Api("/auth/logout") as account_api: status, res = account_api.post() if status == 200: print("Logging out.") self.close()
def __init__(self): __host = getConfPart("db","host") __user = getConfPart("db","user") __password = getConfPart("db","password") __dbName = getConfPart("db","dbName") self.api = Api(__host,__user,__password,__dbName) self.userId = None
def attempt_create(self, first, last, username, pwd): api: Api = Api("/account", True) auth_dict = { "firstname": first, "lastname": last, "email": username, "password": pwd } try: status, res = api.post(auth_dict) except ConnectionRefusedError: self.create.create_hint.setText( "Connection refused, please contact your system administrator") except ConnectionError: # From requests library self.create.create_hint.setText( "Could not connect to the share resources server") finally: if status == 200: # timer = QTimer() # timer.timeout.connect(self.cancel_action) # timer.start(900) # if timer: # Accept and close parent window self.attempt_login(username, pwd) else: self.create.create_hint.setText( "Email/password combination already in use")
def server_is_up(): domain = Api().domain port = Api().port from requests import get status_request = str( get(f"http://{domain}:{port}/api/v1/").text.encode( 'utf-8')).lower() # All of if all([ bool(txt) for txt in ['api', 'is', 'online'] if txt in str(status_request) ]): return True return False
def __init__(self, cache_folder='cache', database_folder='database'): self.console = Console() install() self.cache = Cache(cache_folder) self.api = Api(self.cache) self.database = Database() self.database_folder = database_folder self.champion_names = None self.selected_champion = '' self.is_running = True
def attempt_login(self, username, pwd): api: Api = Api("/auth/login", True) status, res = api.post({"email": username, "password": pwd}) if status == 200: self.accept() self.close() else: self.login.login_hint.setText( "The email or password you entered is invalid.")
def __init__(self, *args, **kwargs): super(QFrame, self).__init__(*args, **kwargs) with Api("/account") as account: status, res = account.get() self.credits = round(res['customer']['credits'], 4) self.head_img = None self.menu_button = None self._init_ui() self.setStyleSheet(app_style)
def api_request_to(context, request_type, endpoint, payload=None): # -- NOTE: number is converted into integer with Api(endpoint) as api: # request_type = request_type.uppper() if request_type == 'GET': context.res, context.api_status = api.get() elif request_type == "POST": context.res, context.api_status = api.post(payload) elif request_type == "PUT": api.put(payload) elif request_type == "DELETE": context.res, context.api_status = api.delete()
def get_loc(self, args=None): self.status = True location_result = Api.get_location(self.Api) if ('status' in location_result) and (location_result['status'] == True): position = location_result["iss_position"] lat = position["latitude"] lon = position["longitude"] dto_local = datetime.fromtimestamp(location_result["timestamp"]) self.message = "The ISS current location_result at " + str( dto_local) + " is " + lat + ", " + lon else: self.status = False self.message = "There are error during API interaction. Unable to get a valid response from third party " \ "API, error message: " + location_result['message']
def get_people(self, args=None): self.status = True people_result = Api.get_people_onboard(self.Api) if ('status' in people_result) and (people_result['status'] == True): craft = people_result['people'][0]["craft"] crew = '' for p in people_result['people']: crew = crew + ', ' + p["name"] self.message = "There are " + str( people_result["number"]) + " people aboard the " + str( craft) + ":" + crew[1:] else: self.status = False self.message = "There are error during API interaction. Unable to get a valid response from third party " \ "API, error message: " + people_result['reason']
def get_dashboard_data(self): with Api("/account") as account: status, res = account.get() if status == 200 and isinstance( res, dict ) and "customer" in res and "firstname" in res['customer']: # Insert comma here so we can default to nameless greeting if api fails. self.username = f", {res['customer']['firstname'].capitalize()}" self.total_balance = round(res['customer']['credits'], 4) else: self.username = "******" self.total_balance = 0 with Api("/resources") as resources: status, res = resources.get() if status == 200 and isinstance(res, dict) and "resources" in res: for rsrc in res["resources"]: if str(rsrc['status']) == "ALIVE": self.running_machines += 1 else: self.dead_machine += 1 with Api("/jobs") as jobs: status, res = jobs.get() if status == 200 and isinstance(res, dict) and "jobs" in res: for job in res["jobs"]: if str(job['status']) == "FINISHED": self.finished_jobs += 1 elif str(job['status']) == "RUNNING": self.running_jobs += 1 else: self.killed_jobs += 1
def __init__(self, *args, **kwargs): super(QFrame, self).__init__(*args, **kwargs) # variable self.overview = None # section self.profit_history_frame = None # section self.cost_history_frame = None # section self.profit_history = None # table widget self.cost_history = None # table widget self.greeting = add_greeting() # param string self.username = "" # param string self.total_balance = 15 # param number self.estimated_profit = 30 # param number self.estimated_cost = 20 # param number self.running_machine = 5 # param number self.panic_machine = 2 # param number self.finished_job = 3 # param number self.running_job = 2 # param number self.panic_job = 0 # param number account_api = Api("/account") status, res = account_api.get() if status == 200: # Insert comma here so we can default to nameless greeting if api fails. self.username = f", {res['customer']['firstname'].capitalize()}" # TODO: request "Total Balance", "Estimated profit", "Estimated cost" "machine status"from api also # for testing self.username = "******" self._init_ui() self.setStyleSheet(dashboard_style)
def attempt_login(self, username, pwd): with Api("/auth/login") as api: status, res = api.post({"email": username, "password": pwd}) if status == 200: self.accept() elif status == 401: self.login.login_hint.setText( "The email or password you entered is invalid.") # Only other status API will return is an error, so let the user know else: self.login.login_hint.setText( "There was an error while trying to log in. Please try again." ) print(status)
def test_credential_store(self): from os import path if self.server_is_up(): with Api('/account', auth=True) as api: new_user = { 'firstname': 'firstname', 'lastname': 'lastname', 'email': '*****@*****.**', 'password': '******' } status, res = api.post(new_user) self.assertEqual(status, 200) self.assertTrue(path.exists(Api.store_path), True) # Clean up api.delete()
def _fetch_job_data(self): self.list.clean_table() with Api("/resources") as api: status, res = api.get() # load data to list # data format: [machine_name, ip_address, cpu_gpu, cores, ram, price, status] if status == 200 and isinstance(res, dict) and "resources" in res: for rsrc in res["resources"]: self.list.add_data([ rsrc['machine_name'], rsrc['ip_address'], str(rsrc['cpus']), str(rsrc['cores']), str(rsrc['ram']), str(rsrc['price']), rsrc['status'] ])
def get_pass(self, args=None): self.status = False self.message = "Wrong amount of arguments provided. Current latitude and longitude should be provided: [" \ "python main.py pass 45 -80] " if len(args) == 2: secs_total = 0 raises = '' latitude = to_float(args[0]) longitude = to_float(args[1]) if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)): pass_result = Api.get_pass_details(self.Api, str(latitude), str(longitude)) if pass_result['status']: for p in pass_result['response']: secs_total = secs_total + int(p["duration"]) moments = "{:0>8}".format( str(timedelta(seconds=p["duration"]))) raises = raises + str( datetime.fromtimestamp(p["risetime"]) ) + " for the " + moments + " (" + str( p["duration"]) + " secs)\n" secs = "{:0>8}".format(str(timedelta(seconds=secs_total))) self.status = True self.message = "The ISS will be overhead of " + str( latitude) + ", " + str( longitude ) + " for the total time of " + secs + " (" + str( secs_total ) + " secs) in the following moments: \n" + raises else: self.message = "Invalid arguments provided: " + pass_result["reason"] + "Please be noted to avoid " \ "0 in latitude and " \ "longitude and latitudes " \ "greater than 71.73 " \ "degrees due to core API " \ "limitations " else: self.message = "Wrong arguments provided. Latitude and longitude should be provided as a valid " \ "numbers: [python main.py pass 45 -80]. Please be noted to avoid 0 in latitude and " \ "longitude and latitudes greater than 71.73 due to core API limitations "
def __init__(self, *args, **kwargs): super(QFrame, self).__init__(*args, **kwargs) self.head_img = None # image filename string with Api("/account") as account_api: status, res = account_api.get() if status == 200: # Insert comma here so we can default to nameless greeting if api fails. self.username = f"{res['customer']['firstname'].capitalize()}" self.credits = round(res['customer']['credits'], 4) else: self.username = "******" self.credit = 15 # parameter integer self.credit_history = None # button self.notification = None # button self.setting_button = None # button self.logout = None # button self._init_ui() self.setStyleSheet(app_style)
def on_submit_button_clicked(self): machine_name = self.workspace.machine_name.text() ip_address = self.workspace.ip_address.text() cpu_gpu = self.workspace.cpu_gpu.text() # cpu_gpu = 0 cores = self.workspace.cores.text() ram = self.workspace.ram.text() if self.price_selected == 0: price = self.auto_price else: price = self.offering_price with Api("/resources") as api: resources_data = { "machine_name": machine_name, "ip_address": ip_address, "ram": ram, "cores": cores, "cpus": cpu_gpu, "price": price, "status": "ALIVE" } status, res = api.post(resources_data) if not status == 200: # log(neat error message of some kind?) # And probably notify the user? pass # add data to list self._fetch_job_data() # switch page self.on_list_clicked()
def test_api_delete(self): with Api('/', domain='255.255.255.256') as api: self.assertTupleEqual(api.delete(), (None, None))
def __init__(self): self.Api = Api() self.helpers = service self.status = True self.message = ''
def test_api_get(self): # self.assertTrue(self.server_is_up()) with Api('/', domain='255.255.255.256') as api: self.assertTupleEqual(api.get(), (None, None))
from src.api import Api from src.permission import Permission from src.person import Person from src.project import Project from src.uplink import Uplink if __name__ == "__main__": #singup user = Api(username="******", password="******") user.signup() print(user._signup) #login user.login() print(user.access_token) print(user.headers) #update accessToken user.renew() print(user._renew) #login pd = Person("pd", "123456") pd.api.login() print(pd.api.headers) print(pd.api.access_token) print(pd.api.host) connection = pd.api print(connection)
from src import cron from src.api import Api api = Api() def fetch_photo(): api.fetch_photo() @cron.route('/worker', methods=['GET']) def scheduler_worker(): fetch_photo() return 'fetch photo...'
class Client(): def __init__(self): __host = getConfPart("db","host") __user = getConfPart("db","user") __password = getConfPart("db","password") __dbName = getConfPart("db","dbName") self.api = Api(__host,__user,__password,__dbName) self.userId = None def createListPrompt(self): listName = input("create > ") #Check if that list name is unique try: namesOfExistingLists = self.api.getLists(self.userId,["listName"]) except ValueError as e: print(e) return False if (listName,) in namesOfExistingLists: print("List name already exists") return False self.api.createList(listName,self.userId) def addListItemPrompt(self): listToAddTo = input("add - list name > ") itemContents = input("add - item > ") listId = self.api.getListId(listToAddTo) #Last arg (0) is to say this item hasn't been completed self.api.saveListItem(listId,itemContents,0) #Print all the lists in the db def listListsPrompt(self): try: listNames = self.api.getLists(self.userId,["listName"]) except ValueError as e: print(e) return False for i in range(0,len(listNames)): print("{}: {}".format(i,listNames[i][0])) def listItemsPrompt(self): listName = input("todos - list name > ") listId = self.api.getListId(listName) listItems = self.api.getListItems(listId,["content","completed"]) for i in range(0,len(listItems)): completed = "" if listItems[i][1] == 1: completed = "✓" elif listItems[i][1] == 0: completed = "X" print("{}: {} {}".format(i,completed,listItems[i][0])) def removeListItemPrompt(self): listName = input("rmt - listName > ") listId = self.api.getListId(listName) listItems = self.api.getListItems(listId,["todoId"]) todoToRemove = int(input("rmt - todo number > ")) if todoToRemove >= len(listItems): print("todo number is out of range") return False else: self.api.removeListItem(listItems[todoToRemove][0]) def removeListPrompt(self): listName = input("rml - list name > ") listId = self.api.getListId(listName) self.api.removeList(listId) def markListItemPrompt(self): listName = input("mark - list name > ") listId = self.api.getListId(listName) listItems = self.api.getListItems(listId,["todoId","completed"]) todoToMark = int(input("mark - todo number > ")) if todoToMark >=len(listItems): print("todo number is out of range") return False else: if listItems[todoToMark][1] == 0: self.api.markListItem(listItems[todoToMark][0],1) else: self.api.markListItem(listItems[todoToMark][0],0) def showHelp(self): f = open(os.path.abspath('src/help.txt'),'r') print(f.read()) f.close() def runIt(self): choices = { 'add':self.addListItemPrompt, 'create':self.createListPrompt, 'lists':self.listListsPrompt, 'todos':self.listItemsPrompt, 'rmt':self.removeListItemPrompt, 'rml':self.removeListPrompt, 'mark':self.markListItemPrompt, 'exit':sys.exit, 'help':self.showHelp } #If a userId is already set then use the same user if self.userId == None: userName = input("User name > ") password = getpass.getpass("Password > ") if self.api.validateUser(userName,password): self.userId = self.api.getUserId(userName) else: print("Authentication Failed") while True: try: decision = input("> ") try: func = choices.get(decision,self.runIt) func() except ValueError as e: print("Value error occued {}".format(e)) except KeyboardInterrupt: sys.exit(1)