def send_message(message): print(message) send_message_url = ( "https://api.telegram.org/bot%s/sendMessage?chat_id=%s&text=%s" % (secrets.telegram.token, secrets.telegram.chat_id, message) ) curl.get(send_message_url)
def main(): lcd.clear() lcd.setBrightness(800) lcd.setTextColor(lcd.WHITE, lcd.BLACK) lcd.font('SFArch_48.fon') lcd.print('BTC Price', lcd.CENTER, 25, lcd.ORANGE) prev_price = '' timereset = time.ticks_ms() + (60 * 1000) while True: if not m5cloud.idle(): break try: # btc_data = get_btc_price() gc.collect() lcd.triangle(300, 0, 319, 0, 319, 19, lcd.YELLOW, lcd.YELLOW) r = curl.get('http://api.m5stack.com/btc') lcd.triangle(300, 0, 319, 0, 319, 19, lcd.BLUE, lcd.BLUE) btc_data = ujson.loads(r[2]) print(btc_data) print('') if btc_data: # Max price high = btc_data['high'] high = high[:(high.find('.') + 3)] lcd.font(lcd.FONT_DejaVu18) lcd.print('Max:', 20, 192, lcd.GREEN) lcd.print(high, 5, 215, lcd.GREEN) # Min price low = btc_data['low'] low = low[:(low.find('.') + 3)] lcd.font(lcd.FONT_DejaVu18) lcd.print('Min:', 255, 192, lcd.RED) lcd.print(low, lcd.RIGHT, 215, lcd.RED) # Last Price price = btc_data['last'] if not price == prev_price: lcd.rect(0, 100, 320, 48, lcd.BLACK, lcd.BLACK) lcd.font('SFArch_48.fon') lcd.print('$ ' + price, lcd.CENTER, 100, color=lcd.WHITE) # Symbol _offset = 175 if price > prev_price: lcd.rect(140, _offset, 41, 26, lcd.BLACK, lcd.BLACK) lcd.triangle(160, _offset, 140, _offset + 25, 180, _offset + 25, lcd.GREEN, lcd.GREEN) elif price < prev_price: lcd.rect(140, _offset, 41, 26, lcd.BLACK, lcd.BLACK) lcd.triangle(160, _offset + 25, 140, _offset, 180, _offset, lcd.RED, lcd.RED) prev_price = price except: pass time.sleep(5)
def __request(self, action, api, kwargs, privileged=True): if not self._access_token: raise NotAuthorized # hack for https://github.com/WeCase/WeCase/issues/119 if ( privileged and api in self.PRIVILEGED_APIS and self._authorize_code and ( not self.PRIVILEGED_APIS[api]["identifier_required"] or ( self.PRIVILEGED_APIS[api]["identifier_required"] and (("uid" in kwargs) or ("screen_name" in kwargs)) ) ) ): if "uid" in kwargs and "screen_name" not in kwargs: screen_name = self.__request(self.HTTP_GET, "users/show", {"uid": kwargs["uid"]}, privileged=False).get( "screen_name" ) kwargs["screen_name"] = screen_name del kwargs["uid"] kwargs["source"] = self.application.app_key kwargs["access_token"] = self._authorize_code else: kwargs["access_token"] = self._access_token request_url = self.API % api curl = _Curl() if action == self.HTTP_GET: result = curl.get(request_url, kwargs) elif action == self.HTTP_POST: result = curl.post(request_url, kwargs) elif action == self.HTTP_UPLOAD: image = kwargs.pop("pic") kwargs["pic"] = image.read() image.close() result = curl.post_binary(request_url, kwargs) status_code = curl.get_info(pycurl.RESPONSE_CODE) try: result_json = json.loads(result, object_hook=getable_dict) if not isinstance(result_json, dict): return result_json if "error_code" in result_json.keys(): raise APIError(result_json["error_code"], result_json["error"]) return getable_dict(result_json) except (TypeError, ValueError): if status_code != 200: raise APIError(status_code, "Unknown Error") raise ResultCorrupted
def __request(self, action, api, kwargs, privileged=True): if not self._access_token: raise NotAuthorized # hack for https://github.com/WeCase/WeCase/issues/119 if (privileged and api in self.PRIVILEGED_APIS and self._authorize_code and (not self.PRIVILEGED_APIS[api]["identifier_required"] or (self.PRIVILEGED_APIS[api]["identifier_required"] and (("uid" in kwargs) or ("screen_name" in kwargs))))): if "uid" in kwargs and "screen_name" not in kwargs: screen_name = self.__request( self.HTTP_GET, "users/show", { "uid": kwargs["uid"] }, privileged=False).get("screen_name") kwargs["screen_name"] = screen_name del kwargs["uid"] kwargs["source"] = self.application.app_key kwargs["access_token"] = self._authorize_code else: kwargs["access_token"] = self._access_token request_url = self.API % api curl = _Curl() if action == self.HTTP_GET: result = curl.get(request_url, kwargs) elif action == self.HTTP_POST: result = curl.post(request_url, kwargs) elif action == self.HTTP_UPLOAD: image = kwargs.pop("pic") kwargs["pic"] = image.read() image.close() result = curl.post_binary(request_url, kwargs) status_code = curl.get_info(pycurl.RESPONSE_CODE) try: result_json = json.loads(result, object_hook=getable_dict) if not isinstance(result_json, dict): return result_json if "error_code" in result_json.keys(): raise APIError(result_json["error_code"], result_json["error"]) return getable_dict(result_json) except (TypeError, ValueError): if status_code != 200: raise APIError(status_code, "Unknown Error") raise ResultCorrupted
def getdata(): tft = lcd_tft.tft tft.clear(0xffffff) tft.set_bg(0xffffff) tft.text(tft.CENTER,8,"Weather", color=0xeb4634) tft.line(5, 20, 155, 20, 0x101010) print("collecting data") res = curl.get('http://api.openweathermap.org/data/2.5/weather?id=1260728&appid=40b0fc55c3eef1e8b3f0bba8366d1eff&units=metric',"data.json") print(res[1]) file = open("data.json", "r") data = file.read() parsed = json.loads(data) print( parsed["weather"][1]) tft.text(tft.CENTER,30,parsed["weather"][1], color=0xeb4634) tft.text(tft.CENTER,38,parsed["main"][0], color=0xeb4634)
def _request_authorize_code(self, application): # Encode the username to a URL-encoded string. # Then, calculate its base64, we need it later username_encoded = urllib.parse.quote(self._username) username_encoded = username_encoded.encode("UTF-8") # convert to UTF-8-encoded byte string username_encoded = base64.b64encode(username_encoded) # First, we need to request prelogin.php for some necessary parameters. prelogin = self.PRELOGIN_PARAMETER prelogin['su'] = username_encoded curl = _Curl() try: prelogin_result = curl.get(self.PRELOGIN_URL, prelogin) except pycurl.error: raise NetworkError # The result is a piece of JavaScript code, in the format of # sinaSSOController.preloginCallBack({json here}) prelogin_json = prelogin_result.replace("sinaSSOController.preloginCallBack(", "")[0:-1] prelogin_json = json.loads(prelogin_json) # Second, we request login.php to request for a authenticate ticket login = self.LOGIN_PARAMETER login['su'] = username_encoded login['servertime'] = prelogin_json['servertime'] login['nonce'] = prelogin_json['nonce'] login['rsakv'] = prelogin_json['rsakv'] # One more thing, we need to encrypt the password with extra token # using RSA-1024 public key which the server has sent us. rsa_pubkey_bignum = int(prelogin_json['pubkey'], 16) # the public key is a big number in Hex rsa_pubkey = rsa.PublicKey(rsa_pubkey_bignum, 65537) # RFC requires e == 65537 for RSA algorithm plain_msg = "%s\t%s\n%s" % (prelogin_json['servertime'], prelogin_json['nonce'], self._password) plain_msg = plain_msg.encode('UTF-8') # to byte string cipher_msg = rsa.encrypt(plain_msg, rsa_pubkey) cipher_msg = base64.b16encode(cipher_msg) # to Hex login['sp'] = cipher_msg curl = _Curl() try: login_result = curl.post(self.LOGIN_URL % "ssologin.js(v1.4.15)", login) except pycurl.error: raise NetworkError # the result is a JSON string # if success, Sina will give us a ticket for this authorized session login_json = json.loads(login_result) if "ticket" not in login_json: raise AuthorizeFailed(str(login_json)) oauth2 = self.OAUTH2_PARAMETER oauth2['ticket'] = login_json['ticket'] # it's what all we need oauth2['client_id'] = application.app_key oauth2['redirect_uri'] = application.redirect_uri curl = _Curl() curl.set_option(pycurl.FOLLOWLOCATION, False) # don't follow redirect curl.set_option(pycurl.REFERER, self.AUTHORIZE_URL) # required for auth try: curl.post(self.AUTHORIZE_URL, oauth2) except pycurl.error: raise NetworkError # After post the OAuth2 information, if success, # Sina will return "302 Moved Temporarily", the target is "http://redirect_uri/?code=xxxxxx", # xxxxxx is the authorize code. redirect_url = curl.get_info(pycurl.REDIRECT_URL) if not redirect_url: raise AuthorizeFailed("Invalid Application() or wrong username/password.") authorize_code = redirect_url.split("=")[1] self.authorize_code = authorize_code return authorize_code
import lcd_tft, json, curl tft = lcd_tft.tft tft.clear(0xffffff) tft.set_bg(0xffffff) tft.text(tft.CENTER, 10, "Weather", color=0xeb4634) tft.line(5, 21, 155, 21, 0x101010) print("collecting data") res = curl.get( 'http://api.openweathermap.org/data/2.5/weather?id=1260728&appid=40b0fc55c3eef1e8b3f0bba8366d1eff&units=metric', "weather.json") print(res[0]) print("/n/n") print(res[1])
# the curl library is a simple way to access web servers on the internet # https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/curl import curl #get a file from a webserver http://loboris.eu/ESP32/info.txt response = curl.get('loboris.eu/ESP32/info.txt') if response: #response[0] #return code #print(response[1]) #headers print(response[2]) #body
if timeout > 0: time.sleep_ms(1000) now = time.ticks_ms() while True: if wifi.ifconfig()[0] != '0.0.0.0': print("Connected, IP: {}".format(wifi.ifconfig()[0])) break if time.ticks_ms() - now > timeout: break return wifi wifi = init_wifi("signalhuset", "signal+huset2017") # wifi = init_wifi("HomeBox-10E0_5G", "a6cfdf567") # wifi = init_wifi("AndroidAPAD82", "odon3187") status, header, data = curl.get('api.openweathermap.org/data/2.5/onecall?lat=55.6761&lon=12.5683&exclude=minutely,hourly,current&&units=metric&appid=4641ad3e90202b3e5b93bb82490ca04f') weather = Forecast(json.loads(data)['daily']) servo = machine.PWM(machine.Pin(17), freq=50) pin_r = machine.PWM(machine.Pin(27)) pin_g = machine.PWM(machine.Pin(26)) pin_b = machine.PWM(machine.Pin(25)) def on_data(temp): print(temp[2]) today = json.loads(data)['daily'][0]['weather'][0] print(today['main']) if today['main'] == 'Clear': servo.duty(7) elif today['main'] == 'Clouds': servo.duty(11)
def test_curl_http(): if 0 != curl.get('http://www.example.com')[0]: print('cannot fetch http example.com') else: lcd.print('fetch http example.com done')
def _request_authorize_code(self, application): # Encode the username to a URL-encoded string. # Then, calculate its base64, we need it later username_encoded = urllib.parse.quote(self._username) username_encoded = username_encoded.encode( "UTF-8") # convert to UTF-8-encoded byte string username_encoded = base64.b64encode(username_encoded) # First, we need to request prelogin.php for some necessary parameters. prelogin = self.PRELOGIN_PARAMETER prelogin['su'] = username_encoded curl = _Curl() try: prelogin_result = curl.get(self.PRELOGIN_URL, prelogin) except pycurl.error: raise NetworkError # The result is a piece of JavaScript code, in the format of # sinaSSOController.preloginCallBack({json here}) prelogin_json = prelogin_result.replace( "sinaSSOController.preloginCallBack(", "")[0:-1] prelogin_json = json.loads(prelogin_json) # Second, we request login.php to request for a authenticate ticket login = self.LOGIN_PARAMETER login['su'] = username_encoded login['servertime'] = prelogin_json['servertime'] login['nonce'] = prelogin_json['nonce'] login['rsakv'] = prelogin_json['rsakv'] # One more thing, we need to encrypt the password with extra token # using RSA-1024 public key which the server has sent us. rsa_pubkey_bignum = int(prelogin_json['pubkey'], 16) # the public key is a big number in Hex rsa_pubkey = rsa.PublicKey( rsa_pubkey_bignum, 65537) # RFC requires e == 65537 for RSA algorithm plain_msg = "%s\t%s\n%s" % (prelogin_json['servertime'], prelogin_json['nonce'], self._password) plain_msg = plain_msg.encode('UTF-8') # to byte string cipher_msg = rsa.encrypt(plain_msg, rsa_pubkey) cipher_msg = base64.b16encode(cipher_msg) # to Hex login['sp'] = cipher_msg curl = _Curl() try: login_result = curl.post(self.LOGIN_URL % "ssologin.js(v1.4.15)", login) except pycurl.error: raise NetworkError # the result is a JSON string # if success, Sina will give us a ticket for this authorized session login_json = json.loads(login_result) if "ticket" not in login_json: raise AuthorizeFailed(str(login_json)) oauth2 = self.OAUTH2_PARAMETER oauth2['ticket'] = login_json['ticket'] # it's what all we need oauth2['client_id'] = application.app_key oauth2['redirect_uri'] = application.redirect_uri curl = _Curl() curl.set_option(pycurl.FOLLOWLOCATION, False) # don't follow redirect curl.set_option(pycurl.REFERER, self.AUTHORIZE_URL) # required for auth try: curl.post(self.AUTHORIZE_URL, oauth2) except pycurl.error: raise NetworkError # After post the OAuth2 information, if success, # Sina will return "302 Moved Temporarily", the target is "http://redirect_uri/?code=xxxxxx", # xxxxxx is the authorize code. redirect_url = curl.get_info(pycurl.REDIRECT_URL) if not redirect_url: raise AuthorizeFailed( "Invalid Application() or wrong username/password.") authorize_code = redirect_url.split("=")[1] self.authorize_code = authorize_code return authorize_code
import curl help(curl) def call(data): print(data) a=curl.get('https://www.w3schools.com',caller=call)