def post_tweets(self, tweet): url = 'https://api.twitter.com/1.1/statuses/update.json' tweet = { 'status': tweet } credentials = oauth.connection() requests.post(url, auth=credentials, params=tweet)
def create_param(username, password, application_name, param_name, param_value): """ Create new Parameter :param username: Admin Username :type username: str :param password: Admin Password :type username: str :param application_name: Application Name to which the Parameter is Associated :type application_name: str :param param_name: Parameter Name :type param_name: str :param param_value: Parameter Value :type param_value: str :return: New Param :rtype: dict """ param = requests.post(os.getenv("key_server_site") + "/rest/param/create?app=" + application_name, auth=(username, password), json={ "name": param_name, "value": param_value }) try: assert param.status_code == 201 return param.json() except AssertionError: exit("Problem Creating Param (Check Server Logs for Details) - HTTP Status: %i" % param.status_code)
def create_param(username, password, application_name, param_name, param_value): """ Create new Parameter :param username: Admin Username :type username: str :param password: Admin Password :type username: str :param application_name: Application Name to which the Parameter is Associated :type application_name: str :param param_name: Parameter Name :type param_name: str :param param_value: Parameter Value :type param_value: str :return: New Param :rtype: dict """ param = requests.post(os.getenv("key_server_site") + "/rest/param/create?app=" + application_name, auth=(username, password), json={ "name": param_name, "value": param_value }) try: assert param.status_code == 201 return param.json() except AssertionError: exit( "Problem Creating Param (Check Server Logs for Details) - HTTP Status: %i" % param.status_code)
def set_bridge(bridge_ip=None): try: if not bridge_ip: bridge_ip = utils.search_for_bridge() if not bridge_ip: print( 'No bridges found on your network. Try specifying the IP address.' .encode('utf-8')) return None workflow = Workflow() # Create API user for the workflow r = requests.post('http://{bridge_ip}/api'.format(bridge_ip=bridge_ip), data=json.dumps({'devicetype': 'Alfred 2'}), timeout=3) resp = r.json()[0] if resp.get('error'): print('Setup Error: %s' % resp['error'].get('description').encode('utf-8')) else: workflow.settings['bridge_ip'] = bridge_ip workflow.settings['username'] = resp['success']['username'] print( 'Success! You can now control your lights by using the "hue" keyword.' .encode('utf-8')) except requests.exceptions.RequestException: print('Connection error.'.encode('utf-8'))
def create_app(username, password, application_name): """ Create Application :param username: Admin Username :type username: str :param password: Admin Password :type password: str :param application_name: Application Name to Create :type application_name: str :return: List of all Applications :rtype: dict """ app = requests.post(os.getenv("key_server_site") + "/rest/app/create", auth=(username, password), json={"name": application_name}) try: assert app.status_code == 201 return app.json() except AssertionError: exit( "Problem Creating App (Check Server Logs for Details) - HTTP Status: %i" % app.status_code)
def create_new(admin_username, admin_password, username, password, email): """ Create a new User :param admin_username: Admin Username :type admin_username: str :param admin_password: Admin Password :type admin_password: str :param username: Username for new User :type username: str :param password: Password for New User :type password: str :param email: Email Address for New User :type email: str :return: New User :rtype: dict """ user = requests.post(os.getenv("key_server_site") + "/rest/user/create", auth=(admin_username, admin_password), json={"username": username, "password": base64.b64encode(password), "email": email}) try: assert user.status_code == 201 return user.json() except AssertionError: exit("Problem creating new user (Check Server Logs for Details) - HTTP Status: %i" % user.status_code)
def create_key(username, password, application_name, permissions): """ Create API Key :param username: Admin Username :type username: str :param password: Admin Password :type password: str :param application_name: Name of the Application that will be using the API Key :type application_name: str :param permissions: Permissions for the API Key :type permissions: str :return: Generated API Key :rtype: dict """ key = requests.post( os.getenv("key_server_site") + "/rest/key/issue", auth=(username, password), json={"application_name": application_name, "permissions": permissions}, ) try: assert key.status_code == 201 return key.json() except AssertionError: exit("Problem Creating Key (Check Server Logs for Details) - HTTP Status: %i" % key.status_code)
def create_key(username, password, application_name, permissions): """ Create API Key :param username: Admin Username :type username: str :param password: Admin Password :type password: str :param application_name: Name of the Application that will be using the API Key :type application_name: str :param permissions: Permissions for the API Key :type permissions: str :return: Generated API Key :rtype: dict """ key = requests.post(os.getenv("key_server_site") + "/rest/key/issue", auth=(username, password), json={ "application_name": application_name, "permissions": permissions }) try: assert key.status_code == 201 return key.json() except AssertionError: exit( "Problem Creating Key (Check Server Logs for Details) - HTTP Status: %i" % key.status_code)
def test_commitWithMultipleReferencesButOnlyOneVerb(self): cards = [] names = ["To Be Closed", "To Be Referenced", "Another To Be Referenced"] for name in names: cardInfo = {'name': name, 'idList': PUBLIC_LIST, 'token': TOKEN, 'key': API_KEY} cards.append(requests.post(BASE_URL+"/cards", data=cardInfo).json) cardIds = (cards[0]['idShort'], cards[1]['idShort'], cards[2]['idShort']) message = "Fixed tr#%s, tr#%s, tr#%s " % cardIds commit = {'message': message} self.broker.handleCommit(commit) params = {'actions': 'commentCard', 'members': 'true', 'fields': 'closed'} # First card should be closed idShort = cards[0]['idShort'] card = requests.get(CARD_URL % (self.broker.board, idShort), params=params).json self.assertEqual(card['actions'][0]["data"]["text"], message) self.assertTrue(self.author in card['members']) self.assertTrue(card['closed']) # Second card should not be closed idShort = cards[1]['idShort'] card = requests.get(CARD_URL % (self.broker.board, idShort), params=params).json self.assertEqual(card['actions'][0]["data"]["text"], message) self.assertTrue(self.author in card['members']) self.assertFalse(card['closed']) # Third card should be closed also idShort = cards[2]['idShort'] card = requests.get(CARD_URL % (self.broker.board, idShort), params=params).json self.assertEqual(card['actions'][0]["data"]["text"], message) self.assertTrue(self.author in card['members']) self.assertFalse(card['closed'])
def set_bridge(bridge_ip=None): try: if not bridge_ip: bridge_ip = utils.search_for_bridge() if not bridge_ip: print('No bridges found on your network. Try specifying the IP address.'.encode('utf-8')) return None workflow = Workflow() # Create API user for the workflow r = requests.post( 'http://{bridge_ip}/api'.format(bridge_ip=bridge_ip), data=json.dumps({'devicetype': 'Alfred 2'}), timeout=3 ) resp = r.json()[0] if resp.get('error'): print('Setup Error: %s' % resp['error'].get('description').encode('utf-8')) else: workflow.settings['bridge_ip'] = bridge_ip workflow.settings['username'] = resp['success']['username'] print('Success! You can now control your lights by using the "hue" keyword.'.encode('utf-8')) except requests.exceptions.RequestException: print('Connection error.'.encode('utf-8'))
def retweet(self, retweet): index = len(self.timeline[int(retweet[0])-1]) url = ('https://api.twitter.com/1.1/statuses/retweet/' + self.timeline[int(retweet[0])-1][index-int(retweet[2:])]['id_str'] + '.json' ) credentials = oauth.connection() retweet = requests.post(url, auth=credentials)
def favorite(self, *args): url = 'https://api.twitter.com/1.1/favorites/create.json' index = len(self.timeline[int(args[0][0])-1]) fav = { 'id': self.timeline[int(args[0][0])-1][index-int(args[0][1])]['id_str'] } credentials = oauth.connection() favorite = requests.post(url, auth=credentials, params=fav)
def test_commitWithMultipleReferencesButOnlyOneVerb(self): cards = [] names = [ "To Be Closed", "To Be Referenced", "Another To Be Referenced" ] for name in names: cardInfo = { 'name': name, 'idList': PUBLIC_LIST, 'token': TOKEN, 'key': API_KEY } cards.append( requests.post(BASE_URL + "/cards", data=cardInfo).json) cardIds = (cards[0]['idShort'], cards[1]['idShort'], cards[2]['idShort']) message = "Fixed tr#%s, tr#%s, tr#%s " % cardIds commit = {'message': message} self.broker.handleCommit(commit) params = { 'actions': 'commentCard', 'members': 'true', 'fields': 'closed' } # First card should be closed idShort = cards[0]['idShort'] card = requests.get(CARD_URL % (self.broker.board, idShort), params=params).json self.assertEqual(card['actions'][0]["data"]["text"], message) self.assertTrue(self.author in card['members']) self.assertTrue(card['closed']) # Second card should not be closed idShort = cards[1]['idShort'] card = requests.get(CARD_URL % (self.broker.board, idShort), params=params).json self.assertEqual(card['actions'][0]["data"]["text"], message) self.assertTrue(self.author in card['members']) self.assertFalse(card['closed']) # Third card should be closed also idShort = cards[2]['idShort'] card = requests.get(CARD_URL % (self.broker.board, idShort), params=params).json self.assertEqual(card['actions'][0]["data"]["text"], message) self.assertTrue(self.author in card['members']) self.assertFalse(card['closed'])
def setUp(self): if not hasattr(self, 'broker'): self.broker = TrelloBroker() self.broker.token = TOKEN self.broker.board = PUBLIC_BOARD if not hasattr(self, 'author'): self.author = requests.get(MEMBER_URL).json # Create a test card and store its full and short IDs cardInfo = {'name': 'Test Me', 'idList': PUBLIC_LIST, 'token': TOKEN, 'key': API_KEY} card = requests.post(BASE_URL+"/cards", data=cardInfo).json self.cardIdFull = card['id'] self.cardIdShort = card['idShort']
def referenceCard(self, cardId, commit): """Post the commit message as a comment and assign the author. To perform any update to the card, card's fullID is required instead of shortID. Therefore, need to query the fullID. However, to avoid performing too many requests, a hash map is used to lazy load the full ID. Keyword arguments: cardId -- the id of the card to perform actions to. commit -- the commit dict with message to comment. """ if cardId not in self.__cardMap: """Lazy loading of card's full ID""" card = getCard(self, cardId) self.__cardMap[cardId] = card['id'] post_load = {'text': commit['message'], 'token': self.token, 'key': API_KEY} res = requests.post(COMMENT_URL % (self.__cardMap[cardId]), data=post_load).json authorId = res['idMemberCreator'] post_load = {'value': authorId, 'token': self.token, 'key': API_KEY} requests.post(ASSIGN_MEMBER_URL % self.__cardMap[cardId], data=post_load)
def referenceCard(self, cardId, commit): """Post the commit message as a comment and assign the author. To perform any update to the card, card's fullID is required instead of shortID. Therefore, need to query the fullID. However, to avoid performing too many requests, a hash map is used to lazy load the full ID. Keyword arguments: cardId -- the id of the card to perform actions to. commit -- the commit dict with message to comment. """ if cardId not in self.__cardMap: """Lazy loading of card's full ID""" card = getCard(self, cardId) self.__cardMap[cardId] = card["id"] post_load = {"text": commit["message"], "token": self.token, "key": API_KEY} res = requests.post(COMMENT_URL % (self.__cardMap[cardId]), data=post_load).json authorId = res["idMemberCreator"] post_load = {"value": authorId, "token": self.token, "key": API_KEY} requests.post(ASSIGN_MEMBER_URL % self.__cardMap[cardId], data=post_load)
def get_token(client_key, client_secret, user_token, user_secret): oauth = OAuth1(client_key, client_secret) url = 'https://api.twitter.com/oauth/request_token' token_requests = requests.post(url, auth=oauth) print token_requests credentials = parse_qs(token_requests.content) user_token = credentials.get('oauth_token')[0] user_secret = credentials.get('oauth_token_secret')[0] return user_token, user_secret
def get_access(client_key, client_secret, user_token, user_secret, verifier): url = 'https://api.twitter.com/oauth/access_token' oauth = OAuth1(client_key, client_secret, user_token, user_secret, verifier=verifier) access_request = requests.post(url=url, auth=oauth) credentials = parse_qs(access_request.content) user_token = credentials.get('oauth_token')[0] user_secret = credentials.get('oauth_token_secret')[0] dbm_create(user_token, user_secret)
def setUp(self): if not hasattr(self, 'broker'): self.broker = TrelloBroker() self.broker.token = TOKEN self.broker.board = PUBLIC_BOARD if not hasattr(self, 'author'): self.author = requests.get(MEMBER_URL).json # Create a test card and store its full and short IDs cardInfo = { 'name': 'Test Me', 'idList': PUBLIC_LIST, 'token': TOKEN, 'key': API_KEY } card = requests.post(BASE_URL + "/cards", data=cardInfo).json self.cardIdFull = card['id'] self.cardIdShort = card['idShort']
def lambda_handler(event, context): global config config = read_yaml('./config/config.yaml') log("config was loaded: %s "%(config),9) processed_date = datetime.today().strftime('%Y-%m-%d') s = requests.Session() s.headers.update({'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36'}) login_data = {'username': config["glucologweb"]['username'], 'password': config["glucologweb"]['password'], "timeZoneOffset": config["glucologweb"]["timeZoneOffset"]} glucologwebLoginURL=config["glucologweb"]["loginURL"] log("trying to call %s with %s data"%(glucologwebLoginURL,json.dumps(login_data)),9) res=s.post(glucologwebLoginURL, login_data,headers={'Referer': 'https://www.glucologweb.com/login?lang=en'}) if (res.status_code != 200 or res.url=='https://www.glucologweb.com/login-error') : log ("cannot Login got status code : " + str(res.status_code),1) log ("redirected to : " + res.url,1) return glucologwebDataURL=config["glucologweb"]["dataURL"] + processed_date + '/false' r2 = s.get(glucologwebDataURL,headers={'Referer': 'https://www.glucologweb.com/home'}) if (r2.status_code != 200): log ("cannot retrive data got status code : " + str(r2.status_code),1) return payload = json.loads(r2.content) if (len(payload["entryPoints"][0])<=0): log ("No Data retrived from Glucologweb",4) quit() pay_load_size = len(payload["entryPoints"][0]) - int(config["general"]["numOfReadingToSync"]) payload["entryPoints"][0] = payload["entryPoints"][0][pay_load_size:] direction_values = [0.19, 0.14, 0.08, -0.08, -0.14, -0.19, -999] direction_name = ["DoubleUp", "SingleUp", "FortyFiveUp", "Flat", "FortyFiveDown", "SingleDown", "DoubleDown"] last_y = None last_x = None my_delta = 0.00 cnt = 0 entries=[] for my_value in payload["entryPoints"][0]: entry = {"type": "svg", "device": "gmns-bridge", "direction": "Flat", "filtered": 0, "unfiltered": 0, "noise": 0, "rssi": 100, "utcOffset": 0} my_y = float(my_value["y"]) date_time_str = processed_date + ' ' + my_value["x"] + ':00' date_time_obj = datetime.strptime(date_time_str+' +0000', '%Y-%m-%d %H:%M:%S %z') unix_time = str(int(date_time_obj.timestamp())) + '000' entry["date"] = int(unix_time) entry["dateString"] = date_time_str + " +00:00" if config["glucologweb"]["units"] == "mmol/l": entry["sgv"] = int(round(my_y*18, 0)) else: entry["sgv"] = int(round(my_y, 0)) if last_y: my_delta = my_y - last_y entry["delta"] = round(my_delta*18, 3) idx = 0 for i in direction_values: if my_delta >= i: entry["direction"] = direction_name[idx] break idx += 1 last_y = my_value["y"] last_x = my_value["x"] entries.append(entry) cnt += 1 #entries_json = json.dumps(entries) if (entries): nightscoutURL= config["nightscout"]["URL"] + "/api/v1/entries?token=" + config["nightscout"]["token"] log ("trying to call %s with %s"%(nightscoutURL,json.dumps(entries)),9) x = requests.post( nightscoutURL, json=entries) if x.status_code != 200 : log ("error calling nightscout got http response : %s" %( str(x.status_code)),1) return { 'statusCode': x.status_code, 'body': json.dumps('Data was not loaded! ') } else: return { 'statusCode': 200, 'body': json.dumps('Hello from gmns-Bridge last entry got : %s UTC'% (last_x)) } else: log ("No Data retrived from Glucologweb",4)
def post_files(self, url, files): log.debug('> %s', url) response = requests.post(url, files=files, proxies=self.proxies) response.raise_for_status() return response.json()
def post(self, url, **kwargs): log.debug('> %s\n%s', url, kwargs) response = requests.post(url, kwargs, proxies=self.proxies) response.raise_for_status() return response.json()