def download(url, target, expected_hash): if filesystem.calculate_hash(target) == expected_hash: return count = 0 while filesystem.calculate_hash(TEMP_FILE) != expected_hash: count += 1 if count > 5: os.remove(TEMP_FILE) raise OSError("Aborting download of %s after 5 unsuccessful attempts" % url) http_client.get(url).raise_for_status().download_to(TEMP_FILE) os.rename(TEMP_FILE, target)
def fetch_api_information(self): """Queries the API for information about this app, returns False if app is not publicly listed""" with http_client.get("http://api.badge.emfcamp.org/api/app/%s/%s" % (self.user, self.name)) as response: if response.status == 404: return False self.api_information = response.raise_for_status().json() return self.api_information
def update(): clear() connect() with dialogs.WaitingMessage(text="Downloading full list of library files", title="TiLDA App Library") as message: message.text="Downloading full list of library files" master = http_client.get("http://api.badge.emfcamp.org/firmware/master-lib.json").raise_for_status().json() libs_to_update = [] for lib, expected_hash in master.items(): if expected_hash != filesystem.calculate_hash("lib/" + lib): libs_to_update.append({ "url": "http://api.badge.emfcamp.org/firmware/master/lib/" + lib, "target": "lib/" + lib, "expected_hash": expected_hash, "title": lib }) download_list(libs_to_update, message) apps = get_local_apps() for i, app in enumerate(apps): message.text = "Updating app %s" % app if app.fetch_api_information(): download_app(app, message) dialogs.notice("Everything is up-to-date")
def get_campaigns(self, open_only=False): params = {} if open_only: filters = [dict(name='status', op='eq', val='open')] params['q'] = json.dumps(dict(filters=filters)) response = get(self.api_host + 'rest/campaign', params=params, token=self.token) return response['objects']
def get_campaign_role(self, campaign_id): params = {} filters = [dict(name='user_id', op='eq', val=str(self.user['id'])), dict(name='campaign_id', op='eq', val=str(campaign_id))] params['q'] = json.dumps(dict(filters=filters)) response = get(self.api_host + 'rest/campaign_user', params=params, token=self.token) return response['objects']
def update(): clear() connect() with dialogs.WaitingMessage(text="Downloading full list of library files", title="TiLDA App Library") as message: message.text="Downloading full list of library files" master = http_client.get("http://api.badge.emfcamp.org/firmware/master-lib.json").raise_for_status().json() libs_to_update = [] for lib, expected_hash in master.items(): if expected_hash != filesystem.calculate_hash("lib/" + lib): libs_to_update.append({ "url": "http://api.badge.emfcamp.org/firmware/master/lib/" + lib, "target": "lib/" + lib, "expected_hash": expected_hash, "title": lib }) download_list(libs_to_update, message) apps = get_local_apps() for i, app in enumerate(apps): message.text = "Updating app %s" % app if app.fetch_api_information(): download_app(app, message) dialogs.notice("Everything is up-to-date") main_menu()
def get_answer(self, hit_id): params = {} filters = [dict(name='hit_id', op='eq', val=str(hit_id))] params['q'] = json.dumps(dict(filters=filters)) response = get(self.api_host + 'rest/answer', params=params, token=self.token) return response['objects']
def getPlayerTime(): #url = "http://api.pray.zone/v2/times/today.json?city=bangkok&school=5" url = "http://www.muslimthaipost.com/prayertimes/solaat.php?TYcHwyNDtkQVVUTzttQVVUTzt5QVVUTzsxMzA7MTY2OyMwMDAwRkY7IzAwMDBGRjsjRkZGRkZGOyNGRkZGRkY7I0ZGRkZGRjsjRkZGRkZGOyNGRkZGRkY7IzAwMDAwMDsjMDAwMDAwOyMwMDAwMDA7Ozs7Ozs7Ozs7Ozs7Ozs7OzI7MDswO3BkfFBTOzE7OzE7MS4yO2M2Mw==" r = http_client.get(url) html = r.text line = html.split('<font color=#000000>') return [line[3].split(' ')[0],line[5].split(' ')[0],line[7].split(' ')[0],line[9].split(' ')[0],line[11].split(' ')[0]]
def checkIfMessageDefinitionExists(self, whatName, debug = False): self._getToken(debug) getUrl = "{}/messagedefinition/latest/{}".format(self.connectToURLforCC_In, whatName) if debug: print('Sending endpoint : ', getUrl) auth_header = {'Authorization':'Bearer {}\r\n'.format(self.tokenBearer), 'Accept':'application/json'} resp = http_client.get(getUrl, headers=auth_header, debug = debug) if debug: print (resp.content) resp.close() return resp.getStatus()[0] == 200
def updatingWeather(stat, my_gps, my_display): WEBADDRESS = 'http://api.openweathermap.org/data/2.5/weather?lat=$LATITUDE$&lon=$LONGITUDE$&units=metric&appid=' API = '######API KEY HERE######' if (stat != None): # changing gps coodinates to get the weather status address = WEBADDRESS + API address = address.replace('$LATITUDE$', str(my_gps.latitude_decimal())) address = address.replace('$LONGITUDE$', str(my_gps.longitude_decimal())) try: # get request r = http_client.get(address) r.raise_for_status() # processing get request if (r.status_code == 200): weather_data = r.json() sys = weather_data['sys'] weather_condition = weather_data['weather'] weather_condition = weather_condition[0] weather_main = weather_data['main'] # city my_display.drawString(50, 30, weather_data['name'], font_6x8, my_display.COLOR_WHITE, 1) # country my_display.drawString(65, 40, sys['country'], font_6x8, my_display.COLOR_WHITE, 1) # temp my_display.drawString(50, 50, str(weather_main['temp']) + ' C', font_6x8, my_display.COLOR_WHITE, 1) # pressure my_display.drawString(75, 60, str(weather_main['pressure']), font_6x8, my_display.COLOR_WHITE, 1) # humidity my_display.drawString(75, 70, str(weather_main['humidity']), font_6x8, my_display.COLOR_WHITE, 1) # weather my_display.drawString(70, 80, weather_condition['main'], font_6x8, my_display.COLOR_WHITE, 1) my_display.drawString(20, 90, weather_condition['description'], font_6x8, my_display.COLOR_WHITE, 1) # update status my_display.drawCircle(149, 117, 10, my_display.COLOR_GREEN) else: # update status my_display.drawCircle(149, 117, 10, my_display.COLOR_RED) except: # website problems pycom.rgbled(0x220000) my_display.drawCircle(149, 117, 10, my_display.COLOR_RED) my_gps.stringclean() time.sleep_ms(2000)
def get_campaign_role(self, campaign_id): params = {} filters = [ dict(name='user_id', op='eq', val=str(self.user['id'])), dict(name='campaign_id', op='eq', val=str(campaign_id)) ] params['q'] = json.dumps(dict(filters=filters)) response = get(self.api_host + 'rest/campaign_user', params=params, token=self.token) return response['objects']
def getLatestMessageDefinitions(self, debug = False): self._getToken(debug) getUrl = "{}/messagedefinition/latest".format(self.connectToURLforCC_In) if debug: print('Sending endpoint : ', getUrl) auth_header = {'Authorization':'Bearer {}\r\n'.format(self.tokenBearer), 'Accept':'application/json'} resp = http_client.get(getUrl, headers=auth_header, debug = debug) if debug: print (resp.content) resp.raise_for_status() result = resp.json() resp.close() return result
def download(url, target, expected_hash): if filesystem.calculate_hash(target) == expected_hash: return count = 0 while filesystem.calculate_hash(TEMP_FILE) != expected_hash: count += 1 if count > 5: os.remove(TEMP_FILE) raise OSError("Aborting download of %s after 5 unsuccessful attempts" % url) try: http_client.get(url).raise_for_status().download_to(TEMP_FILE) except OSError: pass # If it already exists the rename will fail try: os.remove(target) except OSError: pass os.rename(TEMP_FILE, target)
def fetch_public_app_api_information(uncached=False): """Returns a dict category => list of apps Uses cached version unless the uncached parameter is set """ global _public_apps_cache if not _public_apps_cache or uncached: response = {} for category, apps in http_client.get("http://api.badge.emfcamp.org/api/apps").raise_for_status().json().items(): response[category] = [app_by_api_response(app) for app in apps] _public_apps_cache = response return _public_apps_cache
def checkIfMessageDefinitionExists(self, whatName, debug=False): self._getToken(debug) getUrl = "{}/messagedefinition/latest/{}".format( self.connectToURLforCC_In, whatName) if debug: print('Sending endpoint : ', getUrl) auth_header = { 'Authorization': 'Bearer {}\r\n'.format(self.tokenBearer), 'Accept': 'application/json' } resp = http_client.get(getUrl, headers=auth_header, debug=debug) if debug: print(resp.content) resp.close() return resp.getStatus()[0] == 200
def request(before, after, uri): dialog(before) drawui() try: url = "http://carboni.io" + uri print("GET: " + url) response = get(url).raise_for_status().content print("EMF number one says: " + repr(response)) dialog("Got a reply from emf number one: " + repr(response)) dialog(after) print("finish!") except Exception as ex: print("Error: " + repr(ex)) dialog("Aw shoot, we got an error: " + repr(ex) + " - it might be that wifi disconnected?")
def getLatestMessageDefinitions(self, debug=False): self._getToken(debug) getUrl = "{}/messagedefinition/latest".format( self.connectToURLforCC_In) if debug: print('Sending endpoint : ', getUrl) auth_header = { 'Authorization': 'Bearer {}\r\n'.format(self.tokenBearer), 'Accept': 'application/json' } resp = http_client.get(getUrl, headers=auth_header, debug=debug) if debug: print(resp.content) resp.raise_for_status() result = resp.json() resp.close() return result
def get_by_id(id, **params): path = '/homology/id/%s' % id return http_client.get(path, **params)
def get_credit_by_campaign(self, campaign_id): response = get(self.api_host + 'user/credit/campaign/'+str(campaign_id), token=self.token) return response
def download(url, target, expected_hash): http_client.get(url).raise_for_status().download_to(TEMP_FILE) os.rename(TEMP_FILE, target)
s = socket.socket() s.connect(addr) s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8')) while True: data = s.recv(100) if data: print(str(data, 'utf8'), end='') else: break s.close() connectWifi() #do_connect() #http_get('http://micropython.org/ks/test.html') r = http_client.get('http://micropython.org/ks/test.html') r.raise_for_status() print(r.status_code) print(r.text) # r.content for raw bytes r = http_client.post( 'https://api-test.hunt-r.tech/thingworx/availability/shifts', json={ "time_zone": "America/CostaRica", "start_date": 0, "end_date": 2 }) print(r.json())
def download_list(items, message_dialog): for i, item in enumerate(items): message_dialog.text = "Downloading %s (%d/%d)" % (item["title"], i + 1, len(items)) http_client.get(item["url"]).raise_for_status().download_to(item["target"])
def get_attachments(self): response = get(self.api_host + 'rest/attachment', token=self.token) return response['objects']
def download(url, target, expected_hash): while True: get(url).raise_for_status().download_to(target) if calculate_hash(target) == expected_hash: break
def get_by_species(species): path = '/info/biotypes/%s' % species return http_client.get(path)
def user_verify_email(self, hash_id): get(self.api_host + 'user/email_verify/' + hash_id)
def get_credit_by_campaign(self, campaign_id): response = get(self.api_host + 'user/credit/campaign/' + str(campaign_id), token=self.token) return response
def get_selections(self): response = get(self.api_host + 'rest/selection', token=self.token) return response['objects']
def get_locations(self): response = get(self.api_host + 'rest/location', token=self.token) return response['objects']
URL = "http://api.badge.emfcamp.org/firmware" while not success: for d in ["apps", "apps/app_library", "lib"]: try: os.remove(d) # Sometimes FS corruption leads to files instead of folders except OSError as e: pass try: os.mkdir(d) except OSError as e: print(e) try: message.text = "Downloading list of libraries" + addendum master = get(URL + "/master.json").raise_for_status().json() libs_to_update = [] for i, (lib, expected_hash) in enumerate(master["lib"].items()): message.text ="Downloading library: %s (%d/%d)%s" % (lib, i + 1, len(master["lib"]), addendum) download(URL + "/master/lib/%s" % lib, "lib/%s" % lib, expected_hash) message.text = "Downloading app library" + addendum download(URL + "/master/apps/app_library/main.py", "apps/app_library/main.py", master["apps"]["app_library"]["main.py"]) success = True except Exception as e: error_string = uio.StringIO() sys.print_exception(e, error_string) error_string = error_string.getvalue() failure_counter += 1
import wifi from http_client import get wifi.connect() try: if wifi.nic().is_connected(): ip = get('http://httpbin.org/ip').raise_for_status().json()["origin"] print("My public IP is %s" % (ip)) except OSError as e: print("Query failed " + str(e))
def get_by_species(species): path = '/info/analysis/%s' % species return http_client.get(path)
def get_by_member_id(id, **params): path = '/genetree/member/id/%s' % id return http_client.get(path, **params)
while not success: for d in ["apps", "apps/app_library", "lib"]: try: os.remove( d ) # Sometimes FS corruption leads to files instead of folders except OSError as e: pass try: os.mkdir(d) except OSError as e: print(e) try: message.text = "Downloading list of libraries" + addendum master = get(URL + "/master.json").raise_for_status().json() libs_to_update = [] for i, (lib, expected_hash) in enumerate(master["lib"].items()): message.text = "Downloading library: %s (%d/%d)%s" % ( lib, i + 1, len(master["lib"]), addendum) download(URL + "/master/lib/%s" % lib, "lib/%s" % lib, expected_hash) message.text = "Downloading app library" + addendum download(URL + "/master/apps/app_library/main.py", "apps/app_library/main.py", master["apps"]["app_library"]["main.py"]) success = True except Exception as e: error_string = uio.StringIO()
def get_by_species_and_symbol(species, symbol, **params): path = '/homology/symbol/%s/%s' % (species, symbol) return http_client.get(path, **params)
def download_list(items): for i, item in enumerate(items): http_client.get(item["url"]).raise_for_status().download_to( item["target"])
def wlanGet(URL): r = http_client.get(URL) r.raise_for_status() print("GET response: " + str(r.status_code))
def get_hits(self): response = get(self.api_host + 'rest/hit', token=self.token) return response['objects']
import wifi TILT_THRESHOLD = -0.4 TILT_PLAY = -0.1 imu = IMU() host = 'http://192.168.0.12:8001' if not wifi.nic().is_connected(): wifi.connect(timeout=20) triggered = False while(True): y = imu.get_acceleration()['y'] if(int(y) < TILT_THRESHOLD): triggered = True elif(y > TILT_PLAY and triggered): try: print('foobar') get(host, timeout=10).raise_for_status() except Exception as e: print('Request Failed {}'.format(str(e))) except OSError as e: print('Request Failed {}'.format(str(e))) finally: triggered = False pyb.delay(500)
def get_by_species_and_region(species, region, **params): path = '/alignment/region/%s/%s' % (species, region) return http_client.get(path, **params)
def get_by_species_and_name(species, name, **params): path = '/xrefs/name/%s/%s' % (species, name) return http_client.get(path, **params)
def get_by_id(id): path = '/archive/id/%s' % id return http_client.get(path)
work_out_dates.extend(date_range()) sorted_dates = sorted(work_out_dates) date_set = set(sorted_dates[0]+timedelta(x) for x in range((sorted_dates[-1]-sorted_dates[0]).days)) missing_dates = sorted(date_set-set(sorted_dates)) if(len(missing_dates) > 0): for missing_date in missing_dates: zero_data.append({'email': email, 'date': missing_date, 'duration': '0' }) return zero_data with open('user_emails.txt') as user_emails: with open('very_new_user_data.txt', 'w') as user_data_file: user_emails_list = filter(None, user_emails.read().split('\n')) for email in user_emails_list: email = email.rstrip() work_out_dates = [] for month in months: data = { 'email': email, 'month': month + ' 2015' } user_data = http.get(url, data) for details in user_data['user']['monthly_summary']: date = datetime.strptime(details['date'], "%Y-%m-%dT%H:%M:%S.%fZ").date() work_out_dates.append(date) duration = details['duration'] print email, month, date, duration user_details.append({'email': email, 'date': date, 'duration': duration }) user_details.extend(zero_datas(email, work_out_dates)) for user_detail in user_details: user_data_file.write(user_detail['email'] + ' ' + user_detail['date'].strftime('%Y/%m/%d') + ' ' + str(user_detail['duration']) + '\n')
def get_by_species_and_symbol(species, symbol, **params): path = '/genetree/member/symbol/%s/%s' % (species, symbol) return http_client.get(path, **params)
'Accept': 'application/json' } payload = 'grant_type=client_credentials&scope=openid' print("Acquiring token") print() r = http_client.post("https://api.enco.io/token", headers=auth_header, textMsg=payload, contentType='application/x-www-form-urlencoded') print(r.text) authInfo = r.json() tokenBearer = authInfo['access_token'] print() print("Using token to retrieve user information") print() auth_header = { 'Authorization': 'Bearer {}\r\n'.format(tokenBearer), 'Accept': 'application/json' } r = http_client.get("https://api.enco.io/userinfo?schema=openid", headers=auth_header) print(r.text) userInfo = r.json() print() print("Hello %s" % userInfo['name']) print("\t%s, %s" % (userInfo['given_name'], userInfo['family_name'])) print("\teMail: %s" % userInfo['email'])