def delayed_scrobble(track,timestamp): # we're supposed to wait 240 seconds or half the length # of the track before actually submitting delay = min(240,track.length / 2) time.sleep(delay) # just re-handshake since it could've been long enough that the # session expired password = open("/home/anders/.lastfm_password").read().strip() newtimestamp = int(time.time()) auth_token = md5hash(md5hash(password) + str(newtimestamp)) handshake_url = "http://post.audioscrobbler.com/?hs=true&p=1.2&c=tst&v=1.0&u=%s&t=%d&a=%s" % ("thraxil",newtimestamp,auth_token) handshake_response = GET(handshake_url) if not handshake_response.startswith("OK"): return # something is wrong (status,session_id,now_playing_url,submission_url,_blah) = handshake_response.split("\n") POST( submission_url, params={'s':session_id, 'a[0]':track.artist.name, 't[0]':track.title, 'b[0]':track.album.name, 'i[0]':timestamp, 'o[0]':'P', 'r[0]':'L', 'm[0]':"", 'l[0]':track.length, 'n[0]':track.track } )
def read_data_from_api(self, myurl): if self.username and self.password: myresponse = GET(myurl, accept=['application/json'], credentials=(self.username, self.password)) else: myresponse = GET(myurl, accept=['application/json']) return json.loads(myresponse)
def lastfm_handshake(): password = open("/home/anders/.lastfm_password").read().strip() timestamp = int(time.time()) auth_token = md5hash(md5hash(password) + str(timestamp)) handshake_url = "http://post.audioscrobbler.com/?hs=true&p=1.2&c=tst&v=1.0&u=%s&t=%d&a=%s" % ("thraxil",timestamp,auth_token) handshake_response = GET(handshake_url) if not handshake_response.startswith("OK"): return ("BAD","","","",0)# something is wrong (status,session_id,now_playing_url,submission_url,_blah) = handshake_response.split("\n") return (status,session_id,now_playing_url,submission_url,timestamp)
def attributes(self, attributes_names='uid', subjectid=''): data = GET( ''.join((self.opensso_url, REST_OPENSSO_ATTRIBUTES)), params = {'attributes_names':attributes_names, 'subjectid':subjectid}, ) attribute_value = '' lines = data.splitlines() for i, line in enumerate(lines): if line == 'userdetails.attribute.name=%s' % attributes_names: attribute_value = lines[i + 1].split('=')[1] break return attribute_value.strip()
def GET(self,q,severity=None,restriction=None): s = self.host + '/' + q params={'apikey':self.apikey} if restriction: params['restriction'] = restriction elif self.restriction: params['restriction'] = self.restriction if severity: params['severity'] = severity elif self.severity: params['severity'] = self.severity ret = GET(s, params) ret = json.loads(ret) """ we're mirroring the perl client lib here """ self.responseCode = ret['status'] """ check to see if we've got a feed object, auto-de(code/compress) it """ if ret['data'].get('result') and ret['data']['result'].get('hash_sha1'): hash = hashlib.sha1() feed = ret['data']['result']['feed'] hash.update(feed) if hash.hexdigest() != ret['data']['result']['hash_sha1']: print "sha1's don't match, possible data corruption... try re-downloading" return feed = zlib.decompress(b64decode(feed)) ret['data']['result']['feed'] = json.loads(feed) """ again, mirroring the perl module with responseContent() """ self.responseContent = json.dumps(ret)
def send_ding_msg(self, msg): from restclient import GET, POST import json import urllib from urllib import quote from datetime import datetime content = { "content": msg + "\n" + datetime.now().strftime('%Y-%m-%d %H:%M:%S') } r = GET( 'https://oapi.dingtalk.com/gettoken?corpid=ding04bb33ecbbcad5f535c2f4657eb6378f&corpsecret=MorKrE3_R8owWfhF62_4dFW3SeV_wmclDAMRZ_lOt2PAZZcx35XF5uAluCL7NzqV' ) access_token = json.loads(r)['access_token'] params = { 'format': 'json', 'method': 'dingtalk.corp.message.corpconversation.asyncsend', 'v': '2.0', 'agent_id': '153447248', 'msgtype': 'text', 'to_all_user': '******' } params['timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S') params['session'] = access_token params['userid_list'] = 'manager1879' params['msgcontent'] = json.dumps(content) POST("https://eco.taobao.com/router/rest", params=params, headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'charset': 'utf-8' })
def lastfm_handshake(): password = open(settings.LASTFM_PASSWORD_FILE).read().strip() timestamp = int(time.time()) auth_token = md5hash(md5hash(password) + str(timestamp)) handshake_url = ( "http://post.audioscrobbler.com/?hs=true&p=1.2&c=" "tst&v=1.0&u=%s&t=%d&a=%s") % ("thraxil", timestamp, auth_token) try: handshake_response = GET(handshake_url) except: return ("BAD", "", "", "", 0) # not responding if not handshake_response.startswith("OK"): return ("BAD", "", "", "", 0) # something is wrong (status, session_id, now_playing_url, submission_url, _blah) = handshake_response.split("\n") return (status, session_id, now_playing_url, submission_url, timestamp)
def usdcnhRate(self): url = 'http://webforex.hermes.hexun.com/forex/quotelist?code=FOREXUSDCNH&column=Code,Price' r = GET(url) data = json.loads(r[1:-2]) rate = float(data['Data'][0][0][1]) / 10000.0 # print '------------------rate---------------\n',rate self.r.set('usdcnhRate', rate)
def attributes(self, attributes_names='uid', subjectid=''): data = GET( ''.join((self.opensso_url, REST_OPENSSO_ATTRIBUTES)), params={ 'attributes_names': attributes_names, 'subjectid': subjectid }, ) attribute_value = '' lines = data.splitlines() for i, line in enumerate(lines): if line == 'userdetails.attribute.name=%s' % attributes_names: attribute_value = lines[i + 1].split('=')[1] break return attribute_value.strip()
def test_get(): HTTPretty.register_uri(HTTPretty.GET, test_url, body=default_body, content_type="text/html") r = GET(test_url) assert r == default_body assert HTTPretty.last_request.method == "GET"
def get_token_info(self): r = GET("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (self.APPID, self.APPSECRET)) js = json.loads(r) if "errcode" not in js: access_token = js["access_token"] expires_in = js["expires_in"] else: print("Can not get the access_token") print(js) return '', None return access_token, expires_in
def test_hello(self): str = GET("http://localhost:27080/_hello") self.assertEquals(type(str).__name__, "str") obj = json.loads(str) self.assertEquals(obj['ok'], 1) self.assertEquals(obj['msg'], "Uh, we had a slight weapons "+ "malfunction, but uh... everything's perfectly "+ "all right now. We're fine. We're all fine here "+ "now, thank you. How are you?")
def results(self): try: response = GET(self.url, accept=['application/json']) except httplib2.ServerNotFoundError as e: print "WARNING : Couldn't connect to JavaMonitor at " + self.url sys.exit(1) try: details = json.loads(response)[0] return details except ValueError as e: print "Unknown status : Couldn't convert JSON to object" sys.exit(3)
def test_find(self): POST("http://localhost:27080/test/mongoose/_insert", params={'docs': '[{"x" : 1},{"x" : 2},{"x" : 3}]'}, async=False) str = GET("http://localhost:27080/test/mongoose/_find") self.assertEquals(type(str).__name__, "str") obj = json.loads(str) self.assertEquals(obj['ok'], 1, str) self.assertEquals(type(obj['id']).__name__, "int", str) self.assertEquals(len(obj['results']), 3, str)
def test_find_sort(self): POST("http://localhost:27080/test/mongoose/_insert", params={'docs': '[{"x" : 1},{"x" : 2},{"x" : 3}]'}, async=False) str = GET("http://localhost:27080/test/mongoose/_find", {"sort": '{"x" : -1}'}) self.assertEquals(type(str).__name__, "str") obj = json.loads(str) self.assertEquals(obj['results'][0]['x'], 3, str) self.assertEquals(obj['results'][1]['x'], 2, str) self.assertEquals(obj['results'][2]['x'], 1, str)
def handle(self, *args, **options): if not settings.DEBUG: print("this should never be run on production") return if not hasattr(settings, 'PROD_BASE_URL'): print("you must set PROD_BASE_URL") return print("fetching content from prod...") url = settings.PROD_BASE_URL + "_pagetree/export/" if args: url = url + "?hierarchy=" + args[0] d = loads(GET(url)) print("removing old pagetree hierarchy...") Hierarchy.objects.all().delete() print("importing the new one...") Hierarchy.from_dict(d) if not hasattr(settings, 'PROD_MEDIA_BASE_URL'): print("in order to pull down uploaded files,") print("you must set PROD_MEDIA_BASE_URL") print("pulling down uploaded files...") base_len = len(settings.PROD_MEDIA_BASE_URL) for upload in d.get('resources', []): relative_path = upload[base_len:] relative_dir = os.path.join(*os.path.split(relative_path)[:-1]) full_dir = os.path.join(settings.MEDIA_ROOT, relative_dir) try: os.makedirs(full_dir) except OSError: pass with open(os.path.join(settings.MEDIA_ROOT, relative_path), "w") as f: print(" writing %s to %s" % (upload, relative_path)) f.write(GET(upload)) print("done")
def send_sms(no, text): while True: if '+62' in no: no = no.replace('+62', '0') no = no.split('/')[0] no = ''.join(re.findall(r'[\d]+', no)) url = 'http://www.freesms4us.com/kirimsms.php' data = {'user':'******', 'pass':'******', 'isi': text, 'no':no} data = urllib.urlencode(data) complete_url = url + '?' + data resp = GET(complete_url) if 'GAGAL' not in resp: break email_send_with_api('SMS REPORT STATUS', '*****@*****.**', 'Resp: %s<br><br>Text:%s' % (resp, text)) return resp
def test_upsert(self): str = POST("http://localhost:27080/test/mongoose/_update", params = {"criteria" : "{}", "newobj" : '{"$set" : {"x" : 1}}', "upsert" : "1", "safe" : "1"}, async = False ) self.assertEquals(type(str).__name__, "str") obj = json.loads(str) self.assertEquals(obj['ok'], 1, str) self.assertEquals(obj['n'], 1, str) str = GET("http://localhost:27080/test/mongoose/_find") obj = json.loads(str) self.assertEquals(obj['ok'], 1, str) self.assertEquals(obj['results'][0]['x'], 1, str)
def logout(self, subjectid): data = GET( ''.join((self.opensso_url, REST_OPENSSO_LOGOUT)), params={'subjectid': subjectid}, )
def getCookieNameForToken(self, ): data = GET(''.join( (self.opensso_url, REST_OPENSSO_COOKIE_NAME_FOR_TOKEN))) return data.split('=')[1].strip()
def get(self, request): graphite_url = (settings.GRAPHITE_BASE + request.META['PATH_INFO'] + "?" + request.META['QUERY_STRING']) return HttpResponse(GET(graphite_url), content_type="text/plain")
def vsersion(): return GET(__API_URL__ + 'version', httplib_params=__httplib_params__)
def isTokenValid(self, tokenid): data = GET( ''.join((self.opensso_url, REST_OPENSSO_IS_TOKEN_VALID)), params={'tokenid': tokenid}, ) return data == 'boolean=true\n'
def getCookieNameForToken(self,): data = GET(''.join((self.opensso_url, REST_OPENSSO_COOKIE_NAME_FOR_TOKEN))) return data.split('=')[1].strip()