def __init__(self): xbmc.Player.__init__(self) utils.post({ 'cmd0': 'PutSurroundMode/MOVIE', 'cmd1': 'aspMainZone_WebUpdateStatus/' }) self.currentMode = "MOVIE"
def do_plant(data,plan=None,onekey=oneKey()): #钱不够导致空仓库,会报错。不想try。 if data: # 3是牧草 没有牧草了 if tail.get_num_of_seed(3)[0][-1] == 0: utils.post(constant.buy_seed_url.format(3, 24)) if plan is None: plan = constant.plant_plan else: #暂时默认plan符合仓库里种子,因为在main里会根据仓库生成plan try: idx=plan.index(constant.plant_plan[0]) except ValueError: idx=-1 if idx==-1: plan.append(constant.plant_plan[0]) landlist_can_plant=find_land_can_plant(data.get('list')) if landlist_can_plant: id,num=plan[0] for land in landlist_can_plant: if num>0: num-=1 note=get_operate_note(constant.plant_seed_in_lan_url.format(land.get('landNum'),id)) print(note) if num==0: del plan[0] if plan:id,num=plan[0] plan[0]=(id,num) pass pass
def ban_user(request): username = request.POST.get('username') user = get_object_or_404(User, username__exact=username) profile = user.get_profile() profile.is_banned = True profile.save() post('http://' + settings.SOCKETIO_SERVER +'/ban-user/', {'username':username}) return HttpResponse('OK')
def send_data(self, data: dict, token: str): """ You must send the answers obtained from the implemented methods, the parameters are defined in the documentation. Important!! We don't tell you if the answer is correct """ url_answer = 'http://dogs.magnet.cl/api/v1/answer/' post(url_answer, data, token)
def set_password(session, phone): url = 'https://candy.one/api/passport/set-password' data = { 'country_code': 'cn', 'password': PASSWORD, 'password2': PASSWORD, 'phone': '+86' + phone, } utils.post(session, url, data)
def sdcx(hphm, hpzl, fdjh): try: url = "https://www.sdmsjw.gov.cn:666/h5-webapp/viosurveil/getclwzList.do" data = { "hphm": hphm, "hpzl": hpzl, "fdjh": fdjh, } a = post(url, data=data) if a["code"] != 0: a = post(url, data=data) b = a["data"].decode() c = json.loads(b) if c["code"] == 1: jsonL = { "code": 2, "msg": "信息输入有误", } return json.dumps(jsonL, ensure_ascii=False) L = [] try: for i in c["info"]: dict = {} # dict["cph"] = i[""] # 车牌号 dict["youwuwz"] = "有违章记录" dict["jffakuan"] = "罚款%s元扣%s" % (i["wfjf"], i["ysfkje"] ) # 扣几分罚多少钱 dict["time1"] = i["wfsj"] # 违章时间 dict["site"] = i["wfdz"] # 违章地址 dict["miaoshu"] = i["wfsm"] # 违章描述 L.append(dict) jsonL = { "code": 1, "msg": "查询成功", "data": L, } return json.dumps(jsonL, ensure_ascii=False) except Exception as e: dict = {} # dict["cph"] = i[""] # 车牌号 dict["youwuwz"] = "没有违章记录" L.append(dict) jsonL = { "code": 1, "msg": "查询成功", "data": L, } return json.dumps(jsonL, ensure_ascii=False) except Exception as e: jsonL = { "code": 0, "msg": "服务器错误", } return json.dumps(jsonL, ensure_ascii=False)
def test_post(self): r = MagicMock(status_code=201) r.json = MagicMock(return_value={}) self.mock_requests.post.return_value = r post(json_page="some_page", action='some_action') self.mock_requests.post.assert_called_with( url="https://testserver.vosfactures.fr/some_page.json", headers={ 'Accept': 'application/json', 'Content-Type': 'application/json' }, data='{"api_token": "anotsorandomapitoken", "some_action": {}}')
def withdraw(session, address=ADDRESS, amount=None): ''' 提取全部余额到指定BigOne账户 ''' if amount is None: amount = get_balance(session) if amount <= 0: return url = 'https://candy.one/api/transaction/withdraw' data = { 'amount': amount, 'recipient_id': address, } utils.post(session, url, data)
def get_order(order_number: str, currency_pair: str): """ 获取订单信息 :param order_number: :param currency_pair: :return: { "result":"true", "order":{ "id":"15088", "status":"cancelled", // 订单状态 open已挂单 cancelled已取消 closed已完成 "currencyPair":"eth_btc", "type":"sell", // 买卖类型 sell卖出, buy买入 "rate":811, // 价格 "amount":"0.39901357", // 买卖数量 "initialRate":811, // 下单价格 "initialAmount":"1" // 下单量 }, "message":"Success" } """ params = { "orderNumber": order_number, "currencyPair": currency_pair } rst = post(PRIVATE_URL, "/getOrder", params) return rst['order']
def sell(currency_pair: str, rate: float, amount: int, order_type=""): """ 下单交易卖出 :param currency_pair: 交易对 ltc_btc :param rate: 价格 :param amount: 交易量 :param order_type: 订单类型,默认是普通; ioc,立即执行否则取消订单 :return: { "result":"true", "orderNumber":"123456", // 订单号,可用于查询/取消订单 "rate":"1000", // 下单价格 "leftAmount":"0", // 剩余数量 "filledAmount":"0.1", // 成交数量 "filledRate":"800.00", // 成交价格 "message":"Success" } """ params = { "currencyPair": currency_pair, "rate": str(rate), "amount": str(amount), "orderType": order_type } if REAL: rst = post(PRIVATE_URL, "/sell", params) return rst else: pprint(params) return {"result": "true", "orderNumber": None}
def balances(): """ 账号资金余额 :return: { "result": "true", "available": { "BTC": "1000", "ETH": "968.8", "ETC": "0", }, "locked": { "ETH": "1" } } """ min_value = 0.001 rst = post(PRIVATE_URL, "/balances", {}) available, locked = rst['available'], rst['locked'] for d in (available, locked): for k in d.keys(): d[k] = round(float(d[k]), 6) available = {k: v for k, v in available.items() if v > min_value} locked = {k: v for k, v in locked.items() if v > min_value} return available, locked
def claim_device(dnac,deviceId, configId, siteId, top_of_stack, imageId, params): # if image is not None and image is not "": # logging.debug("looking for imageid for {}".format(image)) # response = get(dnac, 'image/importation?name={0}'.format(image)) # try: # imageid = response.json()['response'][0]['imageUuid'] # except IndexError: # print("Image:{} not found".format(image)) # return {"Error" : "Imnage:{} nmot found".format(image)} # else: # imageid ='' payload = { "siteId": siteId, "deviceId": deviceId, "type": "Default", "imageInfo": {"imageId": imageId, "skip": False}, "configInfo": {"configId": configId, "configParameters": params} } if top_of_stack is not None: payload['type'] = "StackSwitch" payload['topOfStackSerialNumber'] = top_of_stack logger.debug(json.dumps(payload, indent=2)) claim = post(dnac,"onboarding/pnp-device/site-claim", payload) return claim.json()['response']
def add_dataset(packageName): if packageName in apiHDXDatasetList: print('Dataset ' + packageName + ' already exists, skipping...') return print('Adding dataset ' + packageName) result = post(payload={ "name": packageName, "provider": "hdx", "connectorType": "rest", "tableName": packageName }, endpoint='v1/dataset', api_url=api_url, api_token=api_token) dataset_id = result['data']['id'] status = 'pending' while status == 'pending': get_result = get(payload={}, endpoint='v1/dataset/' + dataset_id, api_url=api_url, api_token=api_token) status = get_result['data']['attributes']['status'] if status == 'pending': print('Sleeping...') time.sleep(2) print(packageName, result)
def create_wallet(address): # 接口里使用了校验和地址,这里如此处理,用于反防作弊 address = eth_utils.to_checksum_address(address) url = 'https://api.bec.com/wallet/create.json' data = { 'address': address, 'app_version': '1.2.1', 'chain_addr': address, 'chain_type': 2, 'gid': 447635452, 'gid_status': 1, 'idfa': utils.gen_uuid(), 'idfv': utils.gen_uuid(), # 0042B207-FE18-4FE9-A66A-A4BF318B78A5 'language': 'zh-Hans', 'model': 'iPhone8,1', 'os_type': 'iOS', 'os_version': '11.1.1', 'type': 2, } ua = 'BECWallet/1.2.1 (bec.meitu.wallet; build:1.2.17; iOS 11.1.1) Alamofire/4.6.0' headers = {'User-Agent': ua} # 戴Tor访问,用于反防作弊 return utils.post(requests, url, data, headers=headers, proxies=settings.TOR)
def add_dataset(dataset): if dataset['code'] in apiUNDatasetList: print('Dataset ' + dataset['code'] + ' already exists, skipping...') return print('Adding dataset ' + dataset['code']) result = post( payload={ "name": dataset['description'], "provider": "un", "connectorType": "rest", "tableName": dataset['code'] }, endpoint='v1/dataset', api_url=api_url, api_token=api_token) dataset_id = result['data']['id'] status = 'pending' while status == 'pending': get_result = get(payload={}, endpoint='v1/dataset/' + dataset_id, api_url=api_url, api_token=api_token) status = get_result['data']['attributes']['status'] if status == 'pending': print('Sleeping...') time.sleep(2) print(dataset, result)
def pull_request(message=None, base=GIT_DEFAULT_BASE): print(cyan("Sending pull request to %s/%s." % (GIT_REMOTE_NAME, base))) if confirm(green('Default message: %s' % get_commit_message(message=message))): title = get_commit_message(message=message) else: title = get_commit_message(message=prompt(green("Enter message: "))) data = { "title": title, "body": "", "head": "{user}:{branch}".format(user=GITHUB['user'], branch=get_branch_name()), "base": base } response = post(url=GITHUB['urls']['pull_request'], data=json.dumps(data)) if response.status_code == 201: print(cyan("Pull Request was sent to %s/%s." % (GIT_REMOTE_NAME, base))) elif response.status_code == 422: print(cyan("Pull-request was sent before.")) else: print(response)
def add_device(dnac, name, serial, pid, top_of_stack): if top_of_stack is None: stack = False else: stack = True payload = [{ "deviceInfo": { "hostname": name, "serialNumber": serial, "pid": pid, "sudiRequired": False, "userSudiSerialNos": [], "stack": stack, "aaaCredentials": { "username": "", "password": "" } } }] logger.debug(json.dumps(payload)) device = post(dnac, "onboarding/pnp-device/import", payload) try: deviceId = device.json()['successList'][0]['id'] except IndexError as e: print ('##SKIPPING device:{},{}:{}'.format(name, serial, device.json()['failureList'][0]['msg'])) deviceId = None return deviceId
def onPlayBackStarted(self): if (self.isPlayingAudio() and self.currentMode != "MUSIC"): utils.log('Changing to Music Mode', xbmc.LOGINFO) utils.post({ 'cmd0': 'PutSurroundMode/MUSIC', 'cmd1': 'aspMainZone_WebUpdateStatus/' }) self.currentMode = "MUSIC" if (self.isPlayingVideo() and self.currentMode != "MOVIE"): utils.log('Changing to Music Mode', xbmc.LOGINFO) utils.post({ 'cmd0': 'PutSurroundMode/MOVIE', 'cmd1': 'aspMainZone_WebUpdateStatus/' }) self.currentMode = "MOVIE"
def test_apply_normal(client): """attempt to apply new application. 1. test: error isn't returned 2. test: DB is changed target_url: /lotteries/<id> [POST] """ idx = 1 user_info = test_user with client.application.app_context(): target_lottery = Lottery.query.get(idx) index = target_lottery.index token = get_token(client, user_info) with mock.patch('api.routes.api.get_time_index', return_value=index): resp = post(client, f'/lotteries/{idx}', token, group_members=[]) assert resp.status_code == 200 with client.application.app_context(): # get needed objects target_lottery = Lottery.query.get(idx) user = User.query.filter_by(secret_id=user_info['secret_id']).first() # this application should be added by previous 'client.put' application = get_application(user, target_lottery) assert application is not None assert resp.get_json() == application_schema.dump(application)[0]
def make_group(**kwargs): '''Needs the name of the group, cooldown, min and max entities, servName and lbid''' data = { "groupConfiguration": {}, "launchConfiguration": { "type": "launch_server", "args": { "server": { "flavorRef": 3, "imageRef": "c11fdbb2-808a-4aec-bf12-d531ae053139" }, "loadBalancers": [ { "loadBalancerId": 141023, "port": 80 } ] } }, "scalingPolicies": [] } data['groupConfiguration'] = kwargs # print json.dumps(data, indent=4) resp = utils.post(endpoint % (auth_data['id'], 'groups'), data=data, token=auth_data['token']) print resp.status_code, resp.json
def solver(self, url: str): posts = [] res = get("https://taifua.com/") soup = BeautifulSoup(res, features="lxml") for item in soup.select(".list-title"): link = item.select_one("a") posts.append(Post(link.get_text(), link.get("href"), 0)) res = post( "https://taifua.com/wp-admin/admin-ajax.php", { "append": "list-home", "paged": 2, "action": "ajax_load_posts", "query": "", "page": "home", }, ) soup = BeautifulSoup(res, features="lxml") for item in soup.select(".list-title"): link = item.select_one("a") posts.append(Post(link.get_text(), link.get("href"), 0)) return posts
def test_apply_same_period_same_lottery(client): """attempt to apply to the same lottery in the same period 1. test: error is returned target_url: /lotteries/<id> [POST] """ idx = 1 token = login(client, test_user['secret_id'], test_user['g-recaptcha-response'])['token'] with client.application.app_context(): target_lottery = Lottery.query.get(idx) index = target_lottery.index user = User.query.filter_by(secret_id=test_user['secret_id']).first() application = Application(lottery=target_lottery, user_id=user.id) db.session.add(application) db.session.commit() with mock.patch('api.routes.api.get_time_index', return_value=index): resp = post(client, f'/lotteries/{idx}', token, group_members=[]) message = resp.get_json()['message'] assert resp.status_code == 400 assert 'already accepted' in message
def make_policy(groupid, **kwargs): '''Make a scaling policy.''' data = [] data.append(kwargs) resp = utils.post(endpoint % (auth_data['id'], 'groups/%s/policies' % groupid), data=json.dumps(data), token=auth_data['token']) print resp.status_code, resp.json
def claim_device(dnac, deviceId, configId, workflowId, params): payload = { "deviceClaimList": [{ "deviceId": deviceId, "configList": [{ "configId": configId, "configParameters": params }] }], "projectId": None, "workflowId": workflowId, "configId": None, "imageId": None, "populateInventory": True } print json.dumps(payload, indent=2) claim = post(dnac, "onboarding/pnp-device/claim", payload) print claim.json()
def claim_device(dnac, device_id, workflow_id): print('claiming device') payload = { "workflowId": workflow_id, "deviceClaimList": [{ "configList": [{ "configId": "", "configParameters": [] }], "deviceId": device_id }], "populateInventory": True, "imageId": None, "projectId": None, "configId": None } logging.debug(json.dumps(payload)) response = post(dnac, "dna/intent/api/v1/onboarding/pnp-device/claim", payload) return response.json()
def send_data(self, data: dict, token: str): """ You must send the answers obtained from the implemented methods, the parameters are defined in the documentation. Important!! We don't tell you if the answer is correct """ url = 'http://dogs.magnet.cl/api/v1/answer/' myData = { 'totalBreeds': data['total_breeds'], 'totalDogs': data['total_dogs'], 'commonBreed': data['common_breed'], 'commonDogName': data['common_dog_name'], } post(url, myData, token)
def send_message(request): if request.user.is_authenticated(): #TODO improve this part and just get the fields needed member = request.user.get_profile() if member.is_banned: return HttpResponseBadRequest() data = cjson.decode(request.read()) message = data['message'] if len(message)>255: return HttpResponseBadRequest() data = {'username':request.member.user.username, 'message':message, 'picture':request.member.img_url } post('http://' + settings.SOCKETIO_SERVER +'/message/', data) return HttpResponse('OK') return HttpResponseBadRequest()
def do_strava_oauth_token_exchange(self): strava_oAuth_url = (f"https://www.strava.com/api/v3/oauth/token?" f"client_id={self.strava_client_id}&" f"client_secret={self.strava_client_secret}&" f"code={self.strava_code}&" "grant_type=authorization_code") json = post(strava_oAuth_url) self.strava_parse_and_save_tokens(json)
def user_request_handler(req): #session_code = request.env['rack.request.query_hash']['code'] # TODO: check req.params['state'] params = { "client_id": "2377e6850d65aa161d1f", "client_secret": "62c8c0af80367464a542c2f4b930499363d4ec7e", "code": req.params['code'], "accept": "json" } headers = { 'Accept': "application/json" } post('https://github.com/login/oauth/access_token', handle_response, params, headers) #req.response.put_header("Location", "https://graph.facebook.com/oauth/authorize?client_id=%s&redirect_uri=%s" % ()) def bla(reply): print dir(reply), reply.message, req.uri EventBus.send('smart.session.manager', {'action': 'start'}, bla) #req.response.put_header("Cookie", "sess_id=") req.response.status_code = 301 req.response.put_header("Location", "/").end()
def invite(invite_id, address): url = 'https://referral.beauty.io/' + invite_id data = { 'address': address, } r = utils.post(requests, url, data) # $('#j-code')[0].value regex = '<input readonly id="j-code" type="text" value="(/[0-9a-zA-Z]+)">' return re.search(regex, r.text).group(1)
def is_register(phone): url = 'https://candy.one/api/user/is_register' data = { 'country_code': 'cn', 'phone': '+86' + phone, } r = utils.post(requests, url, data) data = r.json()['data'] return data['registed'] # data['hasPas']
def cancel_order(order_number: str, currency_pair: str): """ 取消订单 :param order_number: :param currency_pair: :return: {"result":"true","message":"Success"} """ params = {"orderNumber": order_number, "currencyPair": currency_pair} rst = post(PRIVATE_URL, "/cancelOrder", params) return rst
def test_apply_admin(client): """attempt to apply new application as admin test: 403 is returned target_url: /lotteries/<id> [POST] """ idx = 1 token = get_token(client, admin) resp = post(client, f'/lotteries/{idx}', token, group_members=[]) assert resp.status_code == 403
def verify_code_login(session, phone, code): url = 'https://candy.one/api/passport/verify-code-login' data = { 'phone': '+86' + phone, 'country_code': 'cn', 'code': code, 'inviter_id': ENROLL_ID, } r = utils.post(session, url, data) at = r.json()['data']['access_token'] session.headers['x-access-token'] = at
def from_name(cls, name, create=False): payload = {} url = "https://shop.rewe.de/shoppinglist/lists/ajax" response = post(url, payload) shopping_lists = response.get('model').get('shoppingLists') for shopping_list in shopping_lists: if shopping_list.get('name') == name: return cls(shopping_list.get('identification')) if create: return cls.create(name) return None
def predict_cnn_cifar10(dataset_id, model_id): url = 'http://localhost:8080/api/v1/model/{id}/predict'.format(id=model_id) json = {'dataset': dataset_id} resp = utils.post(url, json=json) if resp.status_code == 200: print('Test model status:', resp.status_code, 'data:', resp.text) return resp.json()['id'] raise RuntimeError('status: {code} data: {text}'.format( code=resp.status_code, text=resp.text))
def add_order(): data = utils.get(url=constant.add_market_situation_url) print(data) it = re.finditer('\(\d+/\d+\)', data.get('condition')) flag = True for e in it: print(e.group()) a, b = e.group()[1:-1].split('/') if int(a) - int(b) < 0: flag = False if flag: reponse = utils.post(url=constant.add_market_list_url) print(reponse)
def import_all(): for mp in MPs: if isinstance(mp[4], basestring): payload = {} hluttaw_id = mp[1] person_id = utils.hluttaw_to_popitid(hluttaw_id, base_url) payload['role'] = 'MP' payload['person_id'] = person_id post_label = mp[7] if post_label == 'Bago': post = utils.post('414db6b73e8c40f7836d346c829c9f10',base_url) elif post_label == 'Magway': post = utils.post('bca454c041e9469aab2d91bd7dc7fb93',base_url) else: post = utils.search_post(post_label, base_url) post_id = post['id'] organization_id = post['organization_id'] payload['organization'] = organization_id party = mp[5] party_id = utils.org_name_to_popitid(party,base_url) payload['on_behalf_of_id'] = party_id payload['on_behalf_of'] = party start_date = mp[11] payload['start_date'] = start_date print mp[1] print payload
def pull_request(message=None): print(cyan("Sending pull request...")) if confirm(green('Default message: %s' % get_commit_message(message=message))): title = get_commit_message(message=message) else: title = get_commit_message(message=prompt(green("Enter message: "))) data = { "title": title, "body": "", "head": "{user}:{branch}".format(user=GITHUB['user'], branch=get_branch_name()), "base": "master" } response = post(url=GITHUB['urls']['pull_request'], data=json.dumps(data)) print(cyan(response) if response.status_code != 201 else cyan("Pull Request was sent."))
def claim_device(dnac,deviceId, configId, workflowId, params): payload = { "deviceClaimList": [{ "deviceId": deviceId, "configList": [{ "configId": configId, "configParameters": params }] }], "projectId": None, "workflowId": workflowId, "configId": None, "imageId": None, "populateInventory": True } #print json.dumps(payload, indent=2) claim = post(dnac,"onboarding/pnp-device/claim", payload) return claim.json()['message']
def add_device(dnac, name, serial, pid): payload = [{ "deviceInfo": { "name": name, "serialNumber": serial, "pid": pid, "sudiRequired": False, "userSudiSerialNos": [], "stack": False, "aaaCredentials": { "username": "", "password": "" } } }] device = post(dnac, "onboarding/pnp-device/import", payload) try: deviceId = device.json()['successList'][0]['id'] except IndexError as e: print ('##SKIPPING device:{},{}:{}'.format(name, serial, device.json()['failureList'][0]['msg'])) deviceId = None return deviceId
def add_product(self, product): payload = {"shoppinglistIdentification": self.identification, "nan": product.nan, "quantity": product.quantity} url = "https://shop.rewe.de/shoppinglist/add-product" post(url, payload)
def create(cls, name): payload = {"shoppingListName": name} url = "https://shop.rewe.de/shoppinglist/create/ajax" response = post(url, payload) return cls(response.get('model').get('identification'), name)
#!/usr/bin/env python import utils from get_line import get_new_entry import sys additional = ' #grmlproject, #tip' zsh = ', #zsh' apis = utils.get_apis() entry = get_new_entry() def add_text(orig, add): if len(orig) + len(add) <= 140 or len(orig) > 140: orig += add return orig if entry: entry = entry.rstrip() entry = add_text(entry, additional) if entry.find('zsh') != -1: entry = add_text(entry, zsh) print "Posting: " + entry for api in apis: utils.post(entry, api)
existing_reservations = reservations_view.ReservationsView.reservations cresources = copy.deepcopy(resources) for res in reservations: if res not in existing_reservations: raise Exception("cannot find reservation: " + res) for inst in existing_reservations[res]: resource = cresources[inst["ID"]] ret = ResourcesView()._calculate_capacity(resource, [], [inst["alloc"]]) if ret == {}: raise Exception("Cannot reserve request!") resources = cresources return {} ################################################################ class IRM-Dummy irm_dummy_views = [ResourcesView, ReservationsView, metrics_view.MetricsView] if __name__ == "__main__": mgr = HarnessResourceManager(irm_dummy_views) out = utils.post({"Port": options.PORT, "Name": options.NAME}, "registerManager", 56788) if not isinstance(out, dict) or "result" not in out: print "Error: " + str(out) exit(-1) mgr.run(options.PORT) app = mgr.app()
def remove_product(self, product): payload = {"shoppinglistIdentification": self.identification, "nan": product.nan, "quantity": 0} url = "https://shop.rewe.de/shoppinglist/remove-item/submit" post(url, payload, False)