def mark_test_status(self, test_case_name,status='skipped',test_run_name=None,test_log=None): """ This method will mark the executed step in a test run as Passed / Failed / Skipped in Test Lodge provided test run name and the executed step title. :param test_case_name: The title of the test case for which the status need to be marked in Test Lodge. test_run_name(optional): The run name of the test run which contains the executed step. if None, pylodge will assume the created test run as the test run that has the executed test. status(optional): The execution status of the test. Passed / Failed / Skipped. The default is Skipped. test_log(optional): It is possible to pass a runtime log in to this method. If this argument is appropriately set, then pylodge will also insert the runtime log as a comment for the executed step """ project_id =self.project_id if test_run_name==None: run_id = self.run_id else: run_id = self.fetch_test_run_id(test_run_name) test_case_id = self.fetch_and_save_test_case_id_from_test_name(test_case_name) if status.lower() == 'passed': status_flag = 1 issue_tracker_flag=0 elif status.lower() == 'failed': status_flag = 0 issue_tracker_flag=1 elif status.lower() == 'skipped': status_flag = 2 issue_tracker_flag=0 requests.patch( self._api_url + '/v1/projects/%s/runs/%s/executed_steps/%s.json' % (project_id, run_id, test_case_id), json={ 'executed_step': {'actual_result': 'Test Case %s and the log is \n %s'%(status,test_log), 'passed': status_flag, 'create_issue_tracker_ticket': issue_tracker_flag}}, auth=self._auth_tuple)
def test_connection(cluster, log_write_url=None, girder_token=None): cluster_id = cluster['_id'] cluster_url = '%s/clusters/%s' % (cumulus.config.girder.baseUrl, cluster_id) log = get_cluster_logger(cluster, girder_token) headers = {'Girder-Token': girder_token} try: # First fetch the cluster with this 'admin' token so we get the # passphrase filled out. r = requests.get(cluster_url, headers=headers) check_status(r) cluster = r.json() with get_connection(girder_token, cluster) as conn: status = 'running' # Test can we can connect to cluster output = conn.execute('pwd') if len(output) < 1: log.error('Unable connect to cluster') status = 'error' r = requests.patch( cluster_url, headers=headers, json={'status': status}) check_status(r) except Exception as ex: r = requests.patch(cluster_url, headers=headers, json={'status': 'error'}) # Log the error message log.exception(ex)
def add_reminder(issue, headers, config, dryrun): """ Adds a reminder to the given issue. :param issue: the issue to add a reminder to :param headers: headers to use for requests against API :param config: config to use :param dryrun: whether to only simulate the writing API calls """ until = datetime.datetime.now() + datetime.timedelta(config["grace_period"]) personalized_reminder = config["reminder"].format(author=issue["author"], until=until.strftime("%Y-%m-%d %H:%M")) # post a comment logger.debug("-> Adding a reminder comment via POST %s" % issue["comments_url"]) if not dryrun: requests.post(issue["comments_url"], headers=headers, data=json.dumps({"body": personalized_reminder})) # label the issue if configured if "label" in config and config["label"]: current_labels = list(issue["labels"]) current_labels.append(config["label"]) logger.debug("-> Marking issues as invalid via PATCH %s, labels=%r" % (issue["url"], current_labels)) if not dryrun: requests.patch(issue["url"], headers=headers, data=json.dumps({"labels": current_labels}))
def mark_issue_valid(issue, headers, config, dryrun): """ Marks a (formerly invalidated) issue as valid. :param issue: the issue to mark as valid :param headers: headers to use for requests against API :param config: config to use :param dryrun: whether to only simulate the writing API calls """ label = config.get("label", None) oklabel = config.get("oklabel", None) if not label and not oklabel: return current_labels = list(issue["labels"]) # apply the "incomplete ticket" label if configured if label and label in current_labels: current_labels.remove(label) # apply the "ok ticket" label if configured and issue wouldn't be ignored otherwise if oklabel and not oklabel in current_labels and not (has_ignored_labels(issue, config) or has_ignored_title(issue, config)): current_labels.append(oklabel) logger.debug("-> Marking issue valid via PATCH %s, labels=%r" % (issue["url"], current_labels)) if not dryrun: requests.patch(issue["url"], headers=headers, data=json.dumps({"labels": current_labels}))
def update_prices(request): l_limit = 0.02 treshhold = 0.04 for c in Company.objects.all(): incomplete_tasks = Task.objects.filter(company = c).exclude(id__in=[a.task.id for a in Answer.objects.all()]) timestamp = now() - timedelta(hours=1) answers = Answer.objects.filter(timestamp__gte = timestamp) answers = answers.filter(task__in = [tc for tc in Task.objects.filter(company=c)]) answers = answers.values('task').annotate(dcount=Count('task')) answer_count = len(answers) x = len(incomplete_tasks)/float(answer_count+1) addition = treshhold * (1/(1+math.pow(math.e,(-x+5)))) new_price = addition+l_limit price_json = '{"price":"%f"}' % (new_price) header = {'Content-type': 'application/json'} user = "******" password = "******" count = 0 if incomplete_tasks: print("Sending new price %.2f for tasks of company %s" % (new_price, c.name)) for t in incomplete_tasks: url = "http://localhost:8000/api/tasks/" + str(t.crowdsourcing_id) + "/" count += 1 sys.stdout.write("\r%d/%d" % (count, len(incomplete_tasks))) sys.stdout.flush() requests.patch(url,data=price_json,headers=header,auth=(user,password)) if incomplete_tasks: print("") return HttpResponse('{"text":"Prices successfully updated","success":true}', content_type="application/json")
def test_change_status(): object_id = _create_object() object_url = objects_url + '/' + object_id requests.patch(object_url, json={'status': 'committed'}) r = requests.get(object_url) assert r.status_code == 200 assert r.json()['status'] == 'committed'
def apply_releasability(config, dest, endpoint, crits_id, json): '''apply releasability markings to crits objects via api, return bool to indicate success''' # Skip Crits objects that don't support releasability endpoints_to_ignore = ['relationships'] if endpoint in endpoints_to_ignore: return url = crits_url(config, dest) attempt_certificate_validation = \ config['crits']['sites'][dest]['api']['attempt_certificate_validation'] if not attempt_certificate_validation: requests.packages.urllib3.disable_warnings() data = {'source': config['crits']['sites'][dest]['api']['source']} params = {'api_key': config['crits']['sites'][dest]['api']['key'], 'username': config['crits']['sites'][dest]['api']['user']} data.update(json) if config['crits']['sites'][dest]['api']['ssl']: r = requests.patch(url + endpoint + '/' + crits_id + '/', data=data, params=params, verify=attempt_certificate_validation) else: r = requests.patch(url + endpoint + '/' + crits_id + '/', data=data, params=params) json_output = r.json() result_code = json_output[u'return_code'] success = r.status_code in (200, 201) and result_code == 0 return(success)
def save_user_data(url, uid, name, balance, email): p = { "user[name]": name, "user[email]": email, "user[balance]": balance } requests.patch("{}/users/{}.json".format(url, uid), params=p)
def patch(**kwargs): """Summary Args: **kwargs: Description Returns: TYPE: Description """ path = kwargs.get('path') url = kwargs.get('url') client = kwargs.get('client') oauth_key = kwargs.get('oauth_key', '') fingerprint = kwargs.get('fingerprint') payload = kwargs.get('payload') headers = generate_headers( client=client, oauth_key=oauth_key, fingerprint=fingerprint, ip_address=kwargs.get('ip_address') ) if path: url = client.get_base_path() + path response = requests.patch(url, headers=headers, data=json.dumps(payload)) else: response = requests.patch(url, headers=headers, data=json.dumps(payload)) return determine_response(response=response)
def activate(self, channel): domain = channel.org.get_brand_domain() headers = {"Authorization": "Bearer %s" % channel.config[Channel.CONFIG_AUTH_TOKEN]} # first set our callbacks payload = {"webhooks": {"url": "https://" + domain + reverse("courier.wa", args=[channel.uuid, "receive"])}} resp = requests.patch( channel.config[Channel.CONFIG_BASE_URL] + "/v1/settings/application", json=payload, headers=headers ) if resp.status_code != 200: raise ValidationError(_("Unable to register callbacks: %s", resp.content)) # update our quotas so we can send at 15/s payload = { "messaging_api_rate_limit": ["15", "54600", "1000000"], "contacts_scrape_rate_limit": "1000000", "contacts_api_rate_limit": ["15", "54600", "1000000"], } resp = requests.patch( channel.config[Channel.CONFIG_BASE_URL] + "/v1/settings/application", json=payload, headers=headers ) if resp.status_code != 200: raise ValidationError(_("Unable to configure channel: %s", resp.content))
def TestUser(): url = URL + "/users/me" headers = {} headers["Authorization"] = "Bearer " + access_token values = {"state":"xxxx"} data = json.dumps(values) r = requests.patch(url, data = data, headers = headers) print "set user state:", r.status_code url = URL + "/users/me" headers = {} headers["Authorization"] = "Bearer " + access_token values = {"name":"测试"} data = json.dumps(values) r = requests.patch(url, data = data, headers = headers) print "set user name:", r.status_code url = URL + "/users" headers = {} headers["Authorization"] = "Bearer " + access_token obj = [{"zone":"86", "number":"13800000009", "name":"test9"}, {"zone":"86", "number":"13800000001", "name":"test1"}] r = requests.post(url, data = json.dumps(obj), headers = headers) print "upload contact list:", r.status_code r = requests.get(url, headers = headers) print "users:", r.text
def run(self): while True: req = self.outbound_queue.get() if not req: break if req.request_type == 'GET': params = json.dumps(req.params) requests.get(req.url, params=params) elif req.request_type == 'POST': to_post = json.dumps(req.data) params = json.dumps(req.params) requests.post(req.url, params=params, data=to_post) elif req.request_type == 'PUT': to_put = json.dumps(req.data) params = json.dumps(req.params) requests.put(req.url, params=params, data=to_put) elif req.request_type == 'PATCH': to_patch = json.dumps(req.data) params = json.dumps(req.params) requests.patch(req.url, params=params, data=to_patch) elif req.request_type == 'DELETE': params = json.dumps(req.params) requests.delete(req.url, params=params) else: print 'Invalid request type: %s' % req.request_type
def apply_label(label, issue, headers, dryrun=False): current_labels = list(issue["labels"]) current_labels.append(label) logger.debug("-> Adding a label via PATCH %s, labels=%r" % (issue["url"], current_labels)) if not dryrun: requests.patch(issue["url"], headers=headers, data=json.dumps({"labels": current_labels}))
def POST(self): productline_url = get_productline() url = productline_url + "/qa/session/" + self.playerId headers = { "Content-Type": "application/json" } if self.g2 == "" and self.gV2 == "" and self.g1 == "" and self.gV1 == "": # 不填就是查 print "111" req = requests.get(url, verify=False) return req else: if self.g2 or self.gV2 != "": print "222" contents = { "abtests": { self.gV1: self.g1, self.gV2: self.g2, } } else: print "333" contents = { "abtests": { self.gV1: self.g1 } } print contents requests.patch(url, data=json.dumps(contents), headers=headers, verify=False) req = requests.get(url, verify=False) return req
def migrate_locker(old_locker, new_locker): payload_new = { "locker_rent_confirmed": old_locker.locker_rent_confirmed, "locker_rent_type": old_locker.locker_rent_type, "locker_status": "in_use", "locker_start_time": old_locker.locker_start_time, "locker_end_time": old_locker.locker_end_time, "fk_user": old_locker.fk_user } r_new = requests.patch('{}Lockers/{}/'.format(base_url, new_locker.locker_id), data=payload_new, auth=HTTPBasicAuth(db_user, db_pass)) print 'New locker status change: {}'.format(r_new.status_code) payload_old = { "locker_rent_confirmed": False, "locker_rent_type": None, "locker_start_time": None, "locker_end_time": None, "fk_user": None } new_headers = {'content-type': 'application/json'} r_old = requests.patch('{}Lockers/{}/'.format(base_url, old_locker.locker_id), data=json.dumps(payload_old), headers=new_headers, auth=HTTPBasicAuth(db_user, db_pass)) print 'Old locker status change: {}'.format(r_old.status_code)
def connect_socket(self): while(1): try: self.ws = create_connection(self.socket_url) break except: logging.error('Sensa socket server connection error') time.sleep(15) logging.info('Connected to server') # Set datastreams to listen from server susc_ids = [ds['id'] for ds in self.datastream_suscriptions] logging.debug('Suscribed to datastreams {}'.format(susc_ids)) msg = { 'device_id': self.device_id, 'datastream_suscriptions': susc_ids, 'api_token': self.api_token } self.ws.send(json.dumps(msg)) response = json.loads(self.ws.recv()) logging.debug('Connection response: {}'.format(response)) # Update status on web server payload = json.dumps({'status': self.CONNECTED}) requests.patch(self.device_url, data=payload, headers=self.api_hdrs)
def add_customer_service_staff(staff_uid): secret = md5.new(APP_SECRET).digest().encode("hex") basic = base64.b64encode(str(APP_ID) + ":" + secret) headers = {"Content-Type": "application/json; charset=UTF-8", "Authorization": "Basic " + basic} url = URL + "/applications/%s" % APP_ID obj = {"customer_service": True} r = requests.patch(url, data=json.dumps(obj), headers=headers) assert r.status_code == 200 print "enable customer service success" obj = {"customer_service_mode": 3} r = requests.patch(url, data=json.dumps(obj), headers=headers) assert r.status_code == 200 print "set customer service mode:3 success" url = URL + "/staffs" obj = {"staff_uid": staff_uid, "staff_name": "客服"} r = requests.post(url, data=json.dumps(obj), headers=headers) assert r.status_code == 200 print "add customer service staff success" url = URL + "/staffs/%d" % staff_uid obj = {"state": "online"} r = requests.patch(url, data=json.dumps(obj), headers=headers) assert r.status_code == 200 print "user online"
def update_comment(request, comment_id): headers=get_api_token(request) headers['Content-type']='application/json' data = dict() url = "".join([API_BASE_LINK, 'comments', '/', comment_id, '/']) if request.method == 'GET': params = unquote(request.get_full_path()).split('?')[-1].split('&') for param in params: param=param.split('=') if(len(param)<2): return HttpResponse("Incorrect payload!!!") data[param[0]]=param[1] if request.method == 'POST': method = request.POST.get('_method', '') if str(method).upper() == 'DELETE': requests.delete(url=url, headers=headers) elif str(method).upper() == 'PATCH': for key in request.POST: data[key]=request.POST.get(key, '') requests.patch(url=url, headers=headers, params=data).json() else: url = "".join([API_BASE_LINK, 'comments', '/']) for key in request.POST: data[key]=request.POST.get(key, '') requests.post(url=url, headers=headers, params=data).json() return redirect('/dashboard/')
def listener(self, attr_name, value): import requests lat = str(value.global_relative_frame.lat) lon = str(value.global_relative_frame.lon) server ='http://m2gla-drone.istic.univ-rennes1.fr:8080' url = server +'/intervention/' + args.idIntervention + '/drone' data = '{ "battery": ' + str(vehicle.battery.current) +',"id":"'+ str(args.idDrone) +'","latitude": "' + lat + '","longitude": "' + lon + '"}' headers = {"content-type": "application/json"} #on met a jour la position du drone sur le serveur requests.patch(url, data=data,headers=headers) global nextPoint import urllib,os #si on est arrive a un nouveau point de la mission if vehicle.commands.next != nextPoint: filename = 'tmp/'+str(time.time())+'.png' #recuperation de la limage de la carte a la position du drone urllib.urlretrieve("https://maps.googleapis.com/maps/api/staticmap?center=" +lat +"," + lon + "&zoom=19&size=640x512&maptype=satellite&key=AIzaSyDMiGs7FfMIZANrYC6tBx6D-CFXMt0eY64&style=feature:road.local&scale=1",filename) files = [('file', filename, open(filename, 'rb').read())] data ={"idIntervention":str(args.idIntervention),"latitude":lat ,"longitude":lon} url = server + '/photo/intervention/' + args.idIntervention #on ajoute limage au serveur post_multipart(url,data,files) #suppression de limage os.remove(filename) nextPoint = vehicle.commands.next
def log_test_finish(self, nodeid: str, status: str, exception: str): status = {'passed': 'COMPLETED', 'failed': 'FAILED'}[status] requests.patch(f'{self._revizor_url}/api/tests/cases/{self._testcase_id}', json={ 'status': status, 'error_text': exception }, headers={'Authorization': f'Token {self._token}'})
def test_start_and_complete_external_task(self): # Alternative harnesses which support external tasks can report back # the name and version of the task after they fetch it. task_url = '%srecipes/%s/tasks/%s/' % (self.get_proxy_url(), self.recipe.id, self.recipe.tasks[2].id) name = '/external/example' version = '3.14-1' response = requests.patch(task_url, data=dict(status='Running', name=name, version=version)) self.assertEquals(response.status_code, 200) json = response.json() self.assertEquals(json['status'], 'Running') self.assertEquals(json['name'], name) self.assertEquals(json['version'], version) with session.begin(): session.expire_all() task = self.recipe.tasks[2] self.assertEquals(task.status, TaskStatus.running) self.assertEquals(task.name, name) self.assertEquals(task.version, version) response = requests.patch(task_url, data=dict(status='Completed')) self.assertEquals(response.status_code, 200) self.assertEquals(response.json()['status'], 'Completed') with session.begin(): session.expire_all() task = self.recipe.tasks[2] self.assertEquals(task.status, TaskStatus.completed)
def _exec_cmd_on_remote(self, cmd): """send HTTPS requests to **Github Issues** API :param cmd: dict :rtype: True or False """ success = False url, payload = self._prepare_method_url_and_payload(cmd) if cmd['CMD'] == 'ADD': resp = requests.post(url=url, data=json.dumps(payload), auth=self.auth) success = (resp.status_code == requests.codes.created) elif cmd['CMD'] == 'EDIT': resp = requests.patch(url=url, data=json.dumps(payload), auth=self.auth) success = (resp.status_code == requests.codes.ok) else: # REMOVE resp = requests.patch(url=url, data=json.dumps(payload), auth=self.auth) success = (resp.status_code == requests.codes.ok) return success
def test_invalid_status_transition(self): task_url = '%srecipes/%s/tasks/%s/' % (self.get_proxy_url(), self.recipe.id, self.recipe.tasks[0].id) response = requests.patch(task_url, data=dict(status='Completed')) self.assertEquals(response.status_code, 200) response = requests.patch(task_url, data=dict(status='Running')) self.assertEquals(response.status_code, 409)
def terminate_job(cluster, job, log_write_url=None, girder_token=None): script_filepath = None headers = {'Girder-Token': girder_token} job_id = job['_id'] status_url = '%s/jobs/%s' % (cumulus.config.girder.baseUrl, job_id) try: with get_connection(girder_token, cluster) as conn: if AbstractQueueAdapter.QUEUE_JOB_ID in job: queue_adapter = get_queue_adapter(cluster, conn) output = queue_adapter.terminate_job(job) else: r = requests.patch(status_url, headers=headers, json={'status': JobState.TERMINATED}) check_status(r) if 'onTerminate' in job: commands = '\n'.join(job['onTerminate']['commands']) + '\n' commands = Template(commands) \ .render(cluster=cluster, job=job, base_url=cumulus.config.girder.baseUrl) on_terminate = _put_script(conn, commands + '\n') terminate_output = '%s.terminate.out' % job_id terminate_cmd = 'nohup %s &> %s &\n' % (on_terminate, terminate_output) terminate_cmd = _put_script(conn, terminate_cmd) output = conn.execute(terminate_cmd) conn.remove(on_terminate) conn.remove(terminate_cmd) if len(output) != 1: raise Exception('PID not returned by execute command') try: pid = int(output[0]) except ValueError: raise Exception('Unable to extract PID from: %s' % output) output_message = 'onTerminate error: %s' monitor_process.delay(cluster, job, pid, terminate_output, log_write_url=log_write_url, output_message=output_message, girder_token=girder_token) except Exception as ex: r = requests.patch(status_url, headers=headers, json={'status': JobState.UNEXPECTEDERROR}) check_status(r) get_job_logger(job, girder_token).exception(ex.message) raise finally: if script_filepath and os.path.exists(script_filepath): os.remove(script_filepath)
def emit(self, record): log_record = self.format(record) payload = {'log_record': log_record} try: requests.patch( self.url, json=payload, headers=self.headers, verify=self.ssl_verify) except Exception: self.handleError(record)
def sendPatchRequest(url, data, param=None): '''Call Post to save new data''' if param: response = requests.patch(url, data=json.dumps(data), params=param, headers=headers) elif param is None: response = requests.patch(url, data=json.dumps(data), headers=headers) return response.json(), response.status_code
def sync_price(beer): json_bieres2=copy.deepcopy(json_bieres) if(beers_names_activate[beer].get()):#on check que la biere est bien dans le jeu for i in range(0,len(json_bieres)-1): if(beers_names_activate[json_bieres[i]["slug"]].get()):#si la biere est dans le jeu json_bieres2[i].pop("slug") requests.patch(upont+"/beers/"+json_bieres[i]["slug"],json=json_bieres2[i],headers={"Authorization":"Bearer "+token}) print("Prix changés")
def close_pull_request(req_data): """Closes GitHub pull request.""" requests.patch( '{url}?access_token={token}'.format( url=req_data['pull_request']['url'], token=conf.get('github', 'token')), data='{"state": "closed"}') return
def postResults(results): import requests endpoint = os.getenv('EMPIRICAL_API_URL', 'http://empiricaldev.localtunnel.me/api/x') AUTH = str(os.getenv('EMPIRICAL_AUTH')) EXPERIMENT_ID = str(os.getenv('EXPERIMENT_ID')) endpoint = endpoint + '/' + EXPERIMENT_ID print "Endpoint:", endpoint print "Results:", results requests.patch(endpoint, json=results, headers={'Authorization': 'Basic ' + AUTH})
def testRenameRepo(self): self.createRepo("BestQa", "This is repository for MyOwnPortfolio") url = '%s/repos/MyOwnPortfolio/BestQA' % self.basic_url data = {"name": "BestOfTheBestQA"} requests.patch(url, headers=self.headers, json=data) check_url = '%s/user/repos' % self.basic_url auxiliary.Checking(check_url, 'name', 'BestOfTheBestQA', 60, self.headers).presence()
def scantron_api_query(self, endpoint, **kwargs): """Executes a properly formatted API call to the Scantron API with the supplied arguments.""" url = f"{self.BASE_URL}{endpoint}" # Set HTTP headers. headers = kwargs.get("headers", {}) if not isinstance(headers, dict): raise ValueError( "headers keyword passed to scantron_api_query is not a valid dict object" ) # Merge dictionaries. # https://treyhunner.com/2016/02/how-to-merge-dictionaries-in-python/ headers = {**self.headers, **headers} # Extract HTTP verb, defaults to GET. method = kwargs.get("method", "GET") method = method.upper() # Extract additional parameters, defaults to an empty dictionary. parameters = kwargs.get("params", {}) if not isinstance(parameters, dict): raise ValueError( "params keyword passed to scantron_api_query is not a valid dict object" ) # Extract payload. payload = kwargs.get("payload", "{}") # Used to track number of failed HTTP requests. attempts = 0 while True: try: if method == "GET": response = requests.get( url, headers=headers, params=parameters, json=payload, verify=(not self.api_self_signed), timeout=self.timeout, ) if response.status_code != 200: utility.debug_requests_response(response) break elif method == "POST": response = requests.post( url, headers=headers, params=parameters, json=payload, verify=(not self.api_self_signed), timeout=self.timeout, ) if response.status_code != 201: utility.debug_requests_response(response) break elif method == "PATCH": response = requests.patch( url, headers=headers, params=parameters, json=payload, verify=(not self.api_self_signed), timeout=self.timeout, ) if response.status_code != 200: utility.debug_requests_response(response) break elif method == "PUT": response = requests.put( url, headers=headers, params=parameters, json=payload, verify=(not self.api_self_signed), timeout=self.timeout, ) if response.status_code != 200: utility.debug_requests_response(response) break elif method == "DELETE": response = requests.delete( url, headers=headers, params=parameters, json=payload, verify=(not self.api_self_signed), timeout=self.timeout, ) if response.status_code != 204: utility.debug_requests_response(response) break else: print( f"Invalid HTTP method passed to scantron_api_query: {method}" ) raise ValueError( f"Invalid HTTP method passed to scantron_api_query: {method}" ) except ( requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError, ): attempts += 1 if self.max_attempts < attempts: print( f"Unable to reach Scantron API after {self.max_attempts} tries. Consider increasing the timeout." ) sys.exit(1) else: print( "Packet loss when attempting to reach the Scantron API." ) if self.debug_print: utility.debug_requests_response(response) return response
def perform_patch_request(): """Perform PATCH request to given URL sending given data and return the response""" url = 'https://httpbin.org/patch' data = {'first_name': 'Guido'} response = requests.patch(url, json=data) return response
def driver(data): try: data = json.loads(request.data) messaging_events = data['entry'][0]['messaging'] sender = messaging_events[0]['sender']['id'] #see if it iss an everyone psotback firebase_url = "https://hans-artist.firebaseio.com/admin/" + sender + ".json?auth=" + firebase_credential r = requests.get(firebase_url) print("***about to print json return from admin driver***") print(r.json()) try: print("gonna check on that image first") if r.json()['is_texting_image'] == 'true': sender = messaging_events[0]['sender']['id'] recipient = messaging_events[0]['recipient']['id'] message_timestamp = messaging_events[0]['timestamp'] print("shyo7od see me here") if messaging_events[0]["message"]['attachments'][0][ 'type'] == 'image': #payload = {'recipient': {'id': sender}, 'message': {"text": "We received your image, thanks!"}} # We're going to send this back #r = requests.post('https://graph.facebook.com/v2.6/me/messages/?access_token=' + fbToken, json=payload) print("should not see me here") image_url = messaging_events[0]["message"]['attachments'][ 0]['payload']['url'] firebase_url = "https://hans-artist.firebaseio.com/Alert/2.json?auth=" + firebase_credential print("about to ping for real") r = requests.get(firebase_url) print(r.json()) message_image = r.json()['image_url'] print(message_image) if message_image is None: firebase_payload = {"image_url": image_url} r = requests.patch(firebase_url, data=json.dumps(firebase_payload)) print("this nonya worked") msg = SendMessage(sender) btn_confirm_alert = Button("postback", "Ok", "add_text_postback", "") btn_confirm_fail = Button("postback", "No, send it", "send_image_postback", "") msg.send_buttons("Would you like a caption?: ?", [btn_confirm_alert, btn_confirm_fail]) return "" else: firebase_payload = {"image_url": image_url} r = requests.patch(firebase_url, data=json.dumps(firebase_payload)) print("this nonya worked") msg = SendMessage(sender) btn_confirm_alert = Button("postback", "Ok", "add_text_postback", "") btn_confirm_fail = Button("postback", "No, send it", "send_image_postback", "") msg.send_buttons("Would you like a caption?", [btn_confirm_alert, btn_confirm_fail]) return "" else: print("yo are locked in") # msg = SendMessage(sender) # msg.send_message("plese send in a message") except Exception as e: print(e) try: if r.json()['is_adding_label'] == 'true': if "message" in messaging_events[0]: print("User typed a message.") # Parse user and message information from incoming POST sender = messaging_events[0]['sender']['id'] recipient = messaging_events[0]['recipient']['id'] message_timestamp = messaging_events[0]['timestamp'] message_content = messaging_events[0]['message'][ 'text'].encode("utf-8") print("labeling") #writealert firebase_url = "https://hans-artist.firebaseio.com/Alert/2.json?auth=" + firebase_credential print("about to ping for real") r = requests.get(firebase_url) print(r.json()) message_alert = r.json()['message'] image_info = r.json()['image_url'] print(message_alert) if message_alert is None: firebase_payload = {"message": message_content} r = requests.patch(firebase_url, data=json.dumps(firebase_payload)) print("this nonya worked") msg = SendMessage(sender) btn_confirm_alert = Button( "postback", "Ok", "confirm_label_image_postback", "") btn_confirm_edit = Button("postback", "Edit", "confirm_edit_postback", "") btn_confirm_fail = Button("postback", "Exit", "exit_postback", "") msg.send_buttons( "Can you confirm that you are sending: \n" + str(message_content) + "\n and the picture below?", [ btn_confirm_alert, btn_confirm_edit, btn_confirm_fail ]) payload = { 'recipient': { 'id': sender }, "message": { 'attachment': { 'type': 'image', 'payload': { 'url': image_info } } } } r = requests.post( 'https://graph.facebook.com/v2.6/me/messages/?access_token=' + fbToken, json=payload) return "" else: firebase_payload = {"message": message_content} r = requests.patch(firebase_url, data=json.dumps(firebase_payload)) print("this nonya worked") msg = SendMessage(sender) btn_confirm_alert = Button( "postback", "Ok", "confirm_label_image_postback", "") btn_confirm_edit = Button("postback", "Edit", "confirm_edit_postback", "") btn_confirm_fail = Button("postback", "Exit", "exit_postback", "") msg.send_buttons( "Can you confirm that you are sending: \n" + str(message_content) + "\n and the picture below?", [ btn_confirm_alert, btn_confirm_edit, btn_confirm_fail ]) payload = { 'recipient': { 'id': sender }, "message": { 'attachment': { 'type': 'image', 'payload': { 'url': image_info } } } } r = requests.post( 'https://graph.facebook.com/v2.6/me/messages/?access_token=' + fbToken, json=payload) return "" #image stuff else: print("admin can message whoever") except Exception as e: print(e) try: if r.json()['is_texting_everyone'] == 'true': if "message" in messaging_events[0]: print("User typed a message.") # Parse user and message information from incoming POST sender = messaging_events[0]['sender']['id'] recipient = messaging_events[0]['recipient']['id'] message_timestamp = messaging_events[0]['timestamp'] message_content = messaging_events[0]['message'][ 'text'].encode("utf-8") print("about to ping firebase") #writealert firebase_url = "https://hans-artist.firebaseio.com/Alert/1.json?auth=" + firebase_credential print("about to ping for real") r = requests.get(firebase_url) print(r.json()) message_alert = r.json()['message'] print(message_alert) if message_alert is None: firebase_payload = {"message": message_content} r = requests.patch(firebase_url, data=json.dumps(firebase_payload)) print("this nonya worked") msg = SendMessage(sender) btn_confirm_alert = Button( "postback", "Ok", "confirm_everyone_postback", "") btn_confirm_fail = Button("postback", "Exit", "exit_postback", "") msg.send_buttons( "Can you cofirm that you are sending: \n" + str(message_content) + "\n to everone?", [btn_confirm_alert, btn_confirm_fail]) return "" else: firebase_payload = {"message": message_content} r = requests.patch(firebase_url, data=json.dumps(firebase_payload)) print("this nonya worked") msg = SendMessage(sender) btn_confirm_alert = Button( "postback", "Ok", "confirm_everyone_postback", "") btn_confirm_fail = Button("postback", "Exit", "exit_postback", "") msg.send_buttons( "Can you cofirm that you are sending: \n" + str(message_content) + "\n to everone?", [btn_confirm_alert, btn_confirm_fail]) return "" #image stuff else: print("admin can message whoever") except Exception as e: print(e) if "postback" in messaging_events[0]: print("Admin sent a postback.") postback_action(data) #admin_postbacks(sender) return "" # If the 'message' key exists it's an inbound message from a user. if "message" in messaging_events[0]: print("User typed a message.") # Parse user and message information from incoming POST sender = messaging_events[0]['sender']['id'] recipient = messaging_events[0]['recipient']['id'] message_timestamp = messaging_events[0]['timestamp'] message_content = messaging_events[0]['message']['text'].encode( "utf-8") #see if user sent an image try: #do what we need to do if messaging_events[0]["message"]['attachments'][0][ 'type'] == 'image': payload = { 'recipient': { 'id': sender }, 'message': { "text": "We received your image, thanks!" } } # We're going to send this back r = requests.post( 'https://graph.facebook.com/v2.6/me/messages/?access_token=' + fbToken, json=payload) image_url = messaging_events[0]["message"]['attachments'][ 0]['payload']['url'] except Exception as e: print("caught general exception" + str(e)) #check to see if it is a location try: req = messaging_events[0]['message']['attachments'][0] if req['type'] == 'location': location_local = Location( req['title'], req['payload']['coordinates']['long'], req['payload']['coordinates']['lat'], req['url'], messaging_events[0]['timestamp'], messaging_events[0]['recipient']['id']) payload = { 'recipient': { 'id': sender }, 'message': { "text": "We received your location, thanks! \n" + str(location_local.getLat()) + "\n" + str(location_local.getLong()) } } # We're going to send this back r = requests.post( 'https://graph.facebook.com/v2.6/me/messages/?access_token=' + fbToken, json=payload) except KeyError as e: print("da fuq" + str(e)) except Exception as e: print("caught general excption" + str(e)) #check for quick replys try: if "quick_reply" in messaging_events[0]['message']: quick_reply = messaging_events[0]['message'][ 'quick_reply']['payload'] print("I(SDFDF") print(quick_reply) if quick_reply == 'make_number_subscribers': #ask them if they are user or admin #go through and pull out all subscribers to alert 1 firebase_url = "https://hans-artist.firebaseio.com/users.json?auth=" + firebase_credential r = requests.get(firebase_url) opted_in = [] print(r.json()) for k, v in r.json().items(): print(k) print(v) if v['alerts']['exclusive_content'] == 'on': opted_in.append(k) if len(opted_in) >= 1: msg = SendMessage(sender) msg.send_message("There are currently " + str(len(opted_in)) + " users subscribed") else: msg = SendMessage(sender) msg.send_message( "There are not currently any users subscribed") if quick_reply == 'make_number_users': #ask them if they are user or admin #go through and pull out all subscribers to alert 1 firebase_url = "https://hans-artist.firebaseio.com/users.json?auth=" + firebase_credential r = requests.get(firebase_url) users_opted_in = [] len(list(r.json().items())) number_of_users = len(list(r.json().items())) msg = SendMessage(sender) msg.send_message("There are currently " + str(number_of_users) + " users subscribed") if quick_reply == 'make_main_broadcast': #ask them if they are user or admin make_main_quick_reply(sender) if quick_reply == 'make_main_analytics': #ask them if they are user or admin make_main_analytics(sender) if quick_reply == 'make_main_everyone': message_type_quick_reply(sender) # msg = SendMessage(sender) # btn_one = Button("postback", "ok", "confirm_everyone_quick", "") # msg.send_buttons("Send to everyon?", [btn_one]) #make quick replyas if quick_reply == 'make_main_local': # msg = SendMessage(sender) # btn_one = Button("postback", "ok", "confirm_local", "") # msg.send_buttons([btn_one]) msg = SendMessage(sender) msg.send_message("please give us your location") if quick_reply == 'make_main_specific': city_staty_quick_reply(sender) #send quick reply if quick_reply == 'make_main_checked_in': show_quick_reply(sender) if quick_reply == 'make_show_one': #confirm msg = SendMessage(sender) btn_one = Button("postback", "ok", "confirm_show_one", "") msg.send_buttons("Confirm Show One?", [btn_one]) if quick_reply == 'make_show_two': #ask them if they are user or admin msg = SendMessage(sender) btn_one = Button("postback", "ok", "confirm_show_two", "") msg.send_buttons("Confirm Show Two", [btn_one]) if quick_reply == 'make_show_three': msg = SendMessage(sender) btn_one = Button("postback", "ok", "confirm_show_three", "") msg.send_buttons("Confirm Show Three", [btn_one]) if quick_reply == 'text_quick_reply': # Query Firebase to determine if the message should be routed to a human. try: firebase_url = "https://hans-artist.firebaseio.com/admin/" + sender + ".json?auth=" + firebase_credential r = requests.get(firebase_url) print(r.json()) texting_everyone = r.json()['is_texting_everyone'] print(texting_everyone) if texting_everyone is None: firebase_payload = { "is_texting_everyone": "true" } r = requests.patch( firebase_url, data=json.dumps(firebase_payload)) elif texting_everyone == 'false': firebase_payload = { "is_texting_everyone": "true" } r = requests.patch( firebase_url, data=json.dumps(firebase_payload)) else: print("couldnt set admin data") except Exception as e: print("Exception when patching db " + str(e)) msg = SendMessage(sender) msg.send_message("Please type in your message") if quick_reply == 'photo_quick_reply': #ask them if they are user or admin try: firebase_url = "https://hans-artist.firebaseio.com/admin/" + sender + ".json?auth=" + firebase_credential r = requests.get(firebase_url) print(r.json()) texting_everyone = r.json()['is_texting_image'] print(texting_everyone) if texting_everyone is None: firebase_payload = {"is_texting_image": "true"} r = requests.patch( firebase_url, data=json.dumps(firebase_payload)) elif texting_everyone == 'false': firebase_payload = {"is_texting_image": "true"} r = requests.patch( firebase_url, data=json.dumps(firebase_payload)) else: print("couldnt set admin data") except Exception as e: print("Exception when patching db " + str(e)) msg = SendMessage(sender) msg.send_message("please send your image") if quick_reply == 'state_quick_reply': msg = SendMessage(sender) msg.send_message("Please enter a city or zip") if quick_reply == 'video_quick_reply': print("hello") #ceheck to see if city/state if quick_reply == 'city_quick_reply': msg = SendMessage(sender) msg.send_message("Please enter a city or zip") else: message_content = messaging_events[0]['message'][ 'text'].encode("utf-8") print("hey hey ") if message_content == 'hey': make_broadcast_analytics(sender) elif message_content == '$helloKitty': print("up") else: # msg = SendMessage(sender) # msg.send_message("try something different") # Query API.AI isAdmin = True apiai_response = apiai_query(message_content, sender, messenger_url, MESSENGER_ACCESS_TOKEN, ai, isAdmin) # Store the message to firebase. # Query API.AI #apiai_response = apiai_query(message_content, sender, messenger_url, messenger_access_token, ai) # Store the message to firebase. firebase_url = "https://hans-artist.firebaseio.com/adminmessages.json?auth=" + firebase_credential # sender, message, timestamp firebase_payload = { "sender": sender, "message_content": message_content, "timestamp": time.time() } r = requests.post(firebase_url, data=json.dumps(firebase_payload)) #change model except Exception as e: print("failed in quick reply in admin driver" + str(e)) except Exception as e: print(e)
issue = repo.get_issue(number=issue_number) issue_url = issue.html_url issue_title = issue.title # content payload = {} payload['title'] = issue_title payload['body'] = issue_content # github edit issue api header = {'Authorization': 'token %s' % GITHUB_TOKEN} url = GITHUB_API + "/repos/" + GITHUB_REPO + "/issues/" + str( issue_number) r = requests.patch(url, headers=header, data=json.dumps(payload)) if r.status_code == 200: print("issue update successful: %s" % issue_number) else: print("issue update failed: %s" % issue_number) exit(-1) except GithubException as e: print('get issues: %s error, skip for next' % issue_number) else: #creat issue title = p.name title = re.sub('.md$', '', title, flags=re.IGNORECASE) issue = repo.create_issue(title, issue_content) print("issue create successfule: %s" % issue.number) dictionary[pstr] = issue.number
def patch(self): global url_path global resource_url_path global CIFS global NFS3 global NFS4 global fail_response access_control={} acl=[] acl_payload={} export_policy={} rules=[] clients=[] read_only_rule_list=[] read_write_rule_list=[] payload={} space={} svm={} active_directory_mapping={} performance_service_level={} aggregate={} storage_efficiency_policy={} fail_response=None patch_response_key=[] rules_payload={} payload={} url_path+="/"+key # fetching file-share details and updating multiple values from user input file_share_response = requests.get(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, headers=HEADERS) file_share_json = file_share_response.json() if capacity != None and capacity_in_mb != file_share_json['space']['size']: payload.clear() space['size']=capacity_in_mb; payload['space']=space response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) if performance_service_level_name != None and performance_service_level_name != file_share_json['assigned_performance_service_level']['name']: if performance_service_level_name == UNASSIGNED: performance_service_level_key = UNASSIGNED else: url_psl = server_details + storage_provider_url_path + "performance-service-levels?name=" + performance_service_level_name performance_service_level_key = get_resource_key(url_psl) if (performance_service_level_key == None): module.exit_json(changed=False,meta="Please provide a valid Performance service level name.") payload.clear() performance_service_level['key']=performance_service_level_key payload['performance_service_level']=performance_service_level response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) if storage_efficiency_policy_name != None and storage_efficiency_policy_name != file_share_json['assigned_storage_efficiency_policy']['name']: url_sep = server_details + storage_provider_url_path + "storage-efficiency-policies?name=" + storage_efficiency_policy_name storage_efficiency_policy_key = get_resource_key(url_sep) if (storage_efficiency_policy_key == None): module.exit_json(changed=False,meta="Please provide a valid Storage efficiency policy name.") payload.clear() storage_efficiency_policy['key']=storage_efficiency_policy_key payload['storage_efficiency_policy']=storage_efficiency_policy response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) if permission != None and user_or_group != None: if len(permission) == len(user_or_group): for i in range(0,len(permission)): acl.append({"permission":permission[i].lower(), "user_or_group":user_or_group[i]}) access_control['acl']= acl else: module.exit_json(changed=False,meta="Every user_or_group should have a corresponding permission specified and vice versa.") payload.clear() payload['access_control']=access_control response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) elif permission != None or user_or_group != None: module.exit_json(changed=False,meta="Both user_or_group and permission should be specified.") if export_policy_name != None and cifs == None and index == None and nfsv3 == None and nfsv4 == None and read_only_rule == None and read_write_rule == None and allowed_clients == None: url_export_policy = server_details + datacenter_url_path + "protocols/nfs/export-policies?name=" + export_policy_name + "&svm.name=" + svm_name + "&cluster.name=" + cluster_name export_policy_key = get_resource_key(url_export_policy) if export_policy_key == None: module.exit_json(changed=False,meta="Please provide a valid export policy name.") export_policy['key']=export_policy_key access_control.clear() access_control['export_policy']=export_policy payload.clear() payload['access_control']=access_control response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) elif export_policy_name != None and (cifs != None or index != None or nfsv3 != None or nfsv4 != None or read_only_rule != None or read_write_rule != None or allowed_clients != None): module.exit_json(changed=False,meta="No parameter is allowed with the export policy key.") if read_only_rule != None and read_write_rule != None and allowed_clients != None: export_policy = export_policy_check() access_control.clear() access_control['export_policy']=export_policy payload.clear() payload['access_control']=access_control response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) elif cifs != None or index != None or nfsv3 != None or nfsv4 != None or read_only_rule or read_write_rule or allowed_clients: module.exit_json(changed=False,meta="Parameters: index, read_only_rule, read_write_rule, allowed_clients, must be provided for an Export Policy.") if operational_state != None: payload.clear() payload['operational_state']=operational_state.lower() response = requests.patch(server_details+url_path, auth=(api_user_name,api_user_password), verify=False, data=json.dumps(payload),headers=HEADERS) if response.status_code == 202: patch_response_key.append(response.json().get('job').get('key')) else: fail_response = response.json() self.parse_patch_response(patch_response_key) return patch_response_key
def test_rest_mock(self): url = 'http://my_fake_service/api' update_rest_rules(rest_rules) self.assertTrue(start_http_mock()) r = requests.get(url) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), []) r = requests.get(url + '/1') self.assertEqual(r.status_code, 404) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), {'error': 'Not Found'}) r = requests.get(url + '/1/download') self.assertEqual(r.status_code, 404) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), {'error': 'Not Found'}) r = requests.post(url, data=json.dumps({}), headers=CONTENTTYPE_JSON) self.assertEqual(r.status_code, 400) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), {'error': 'Bad Request'}) r = requests.patch(url + '/1', data=json.dumps({})) self.assertEqual(r.status_code, 404) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), {'error': 'Not Found'}) r = requests.delete(url + '/1') self.assertEqual(r.status_code, 404) self.assertEqual(r.headers, {'content-type': 'text/plain'}) self.assertEqual(r.content, b'Not Found') # add some data r = requests.post(url, data=json.dumps({ 'foo': True, 'bar': 'Python will save the world.', }), headers=CONTENTTYPE_JSON) self.assertEqual(r.status_code, 201) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), { 'id': 1, 'foo': True, 'bar': 'Python will save the world.', }) r = requests.head(url + '/1') self.assertEqual(r.status_code, 200) self.assertEqual(r.headers, { 'content-type': 'text/plain', 'id': '1', }) self.assertEqual(r.content, b'') # recheck list get ... r = requests.get(url) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), [ { 'id': 1, 'foo': True, 'bar': 'Python will save the world.', } ]) r = requests.patch(url + '/1', data=json.dumps({ 'bar': "Python will save the world. I don't know how. But it will." })) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), { 'id': 1, 'foo': True, 'bar': "Python will save the world. I don't know how. But it will.", # noqa }) # missing foo field -> 400 r = requests.put(url + '/1', data=json.dumps({ 'bar': "Python will save the world. I don't know how. But it will." })) self.assertEqual(r.status_code, 400) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), {'error': 'Bad Request'}) r = requests.put(url + '/1', data=json.dumps({ 'foo': False, 'bar': "Python will save the world. I don't know how. But it will." })) self.assertEqual(r.status_code, 200) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), { 'id': 1, 'foo': False, 'bar': "Python will save the world. I don't know how. But it will.", # noqa }) r = requests.get(url + '/1') self.assertEqual(r.status_code, 200) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), { 'id': 1, 'foo': False, 'bar': "Python will save the world. I don't know how. But it will.", # noqa }) r = requests.delete(url + '/1') self.assertEqual(r.status_code, 204) self.assertEqual(r.headers, {'content-type': 'text/plain'}) self.assertEqual(r.content, b'') r = requests.get(url + '/1') self.assertEqual(r.status_code, 404) self.assertEqual(r.headers, {'content-type': 'application/json'}) self.assertEqual(r.json(), { 'error': 'Not Found' })
def run_check(config, mturk, participants, session, reference_time): # get experiment duration in seconds duration_seconds = config.get('duration') * 60.0 * 60.0 # for each participant, if they've been active for longer than the # experiment duration + 5 minutes, we take action. for p in participants: time_active = (reference_time - p.creation_time).total_seconds() if time_active > (duration_seconds + 120): print( "Error: participant {} with status {} has been playing for too " "long and no notification has arrived - " "running emergency code".format(p.id, p.status)) # get their assignment assignment_id = p.assignment_id # First see if we have a bot participant if p.recruiter_id == BotRecruiter.nickname: # Bot somehow did not finish (phantomjs?). Just get rid of it. p.status = "rejected" session.commit() return # ask amazon for the status of the assignment try: assignment = mturk.get_assignment(assignment_id) status = assignment['status'] except Exception: status = None print("assignment status from AWS is {}".format(status)) hit_id = p.hit_id summary = HITSummary( assignment_id=assignment_id, duration=duration_seconds, time_active=time_active, app_id=config.get('id', 'unknown'), when=reference_time, ) # Use a debug messenger for now since Gmail is blocking # outgoing email from random servers: with config.override({'mode': u'debug'}, strict=True): messenger = get_messenger(summary, config) if status == "Approved": # if its been approved, set the status accordingly print("status set to approved") p.status = "approved" session.commit() elif status == "Rejected": print("status set to rejected") # if its been rejected, set the status accordingly p.status = "rejected" session.commit() elif status == "Submitted": # if it has been submitted then resend a submitted notification args = { 'Event.1.EventType': 'AssignmentSubmitted', 'Event.1.AssignmentId': assignment_id } requests.post("http://" + config.get('host') + '/notifications', data=args) # message the researcher: messenger.send_resubmitted_msg() print( "Error - submitted notification for participant {} missed. " "Database automatically corrected, but proceed with caution." .format(p.id)) else: # if it has not been submitted shut everything down # first turn off autorecruit host = config.get('host') host = host[:-len(".herokuapp.com")] args = json.dumps({"auto_recruit": "false"}) headers = { "Accept": "application/vnd.heroku+json; version=3", "Content-Type": "application/json", "Authorization": "Bearer {}".format(config.get("heroku_auth_token")) } requests.patch( "https://api.heroku.com/apps/{}/config-vars".format(host), data=args, headers=headers, ) # then force expire the hit via boto mturk.expire_hit(hit_id) # message the researcher messenger.send_hit_cancelled_msg() # send a notificationmissing notification args = { 'Event.1.EventType': 'NotificationMissing', 'Event.1.AssignmentId': assignment_id } requests.post("http://" + config.get('host') + '/notifications', data=args) print( "Error - abandoned/returned notification for participant {} missed. " "Experiment shut down. Please check database and then manually " "resume experiment.".format(p.id))
def patch(self, path, data={}): auth = (self.id, self.secret) url = self.api_root + '/' + path return requests.patch(url, json=data, auth=auth)
time.sleep(1200) continue else: print("New race! Scraping.") while (1): p = Podesavanja.objects.get(id=1) if (p.is_scraping): print("Waiting for other crawlers to finish scraping") time.sleep(300) else: scaling_payload = { "min": "1", "required": "7", "max": "9", } headers = {'Authorization': 'Zm9ybXVsYTE='} #Zm9ybXVsYTE= rer = requests.patch('http://159.65.107.239:8889/api/scaling', json=scaling_payload, headers=headers) print(rer) time.sleep(60) p.is_scraping = 1 p.save() print("Saving P") get_events() break #get_events()
def req(self, method, url, data=None, params=None): """ make http request with prefixed base url, given data and params """ if params is None: params = {} target_url = urljoin(self.base_url, url) auth_header = "AccessKey %s" % (self.apikey) user_agent = "MedianaSMS/ApiClient/%s Python/%s" % ( self.client_version, sys.hexversion) headers = { "Content-Type": "application/json", "Accept": "application/json", "Authorization": auth_header, "User-Agent": user_agent, } default_headers = requests.utils.default_headers() default_headers.update(headers) methods = { 'DELETE': lambda: requests.delete(target_url, headers=headers, data=json.dumps(data), params=params, timeout=self.timeout), 'GET': lambda: requests.get(target_url, headers=headers, params=params, timeout=self.timeout), 'PATCH': lambda: requests.patch(target_url, headers=headers, data=json.dumps(data), timeout=self.timeout), 'POST': lambda: requests.post(target_url, headers=headers, data=json.dumps(data), timeout=self.timeout), 'PUT': lambda: requests.put(target_url, headers=headers, data=json.dumps(data), timeout=self.timeout) } if method not in methods: raise ValueError(str(method) + " is not in supported methods") try: response = methods[method]() if response.status_code not in self.__supported_status_codes: response.raise_for_status() except RequestException as e: raise HTTPError(e) parsed_response = Response(json.loads(response.content)) errors = parse_errors(parsed_response) if isinstance(errors, Exception): raise errors return parsed_response
jobsite_id = 819 # 157 # 157 type_id = 1 has_document = True # print("contactCode='%s'"%contact["contactCode"]) payload = {"customer": {"customerId": customer_id}} resp = post(url=url + "/v1/csm/cases", headers=headers, json=payload) check_resp(resp) case_id = resp.json()["caseId"] # print("case_id=%s" % case_id) # print("patch description") payload = {"caseDesc": "Ols description Meli"} resp = patch(url="%s/v1/csm/cases/%s/descriptions" % (url, case_id), headers=headers, json=payload) check_resp(resp) # print("patch caseTitle") payload = {"caseTitle": "Ols title Meli"} resp = patch(url="%s/v1/csm/cases/%s/titles" % (url, case_id), headers=headers, json=payload) check_resp(resp) # print("patch casetype") resp = patch(url="%s/v1/csm/cases/%s/casetypes/%s" % (url, case_id, type_id), headers=headers) check_resp(resp)
def close(self): url = f'{HOST}/repos/{self.repo}/issues/{self.number}' parameters = {'state': 'closed'} response = requests.patch(url, json=parameters, headers=self._headers) assert response.ok, response.content
def updateProject(): update = requests.patch(API_URL + "/projects/5775782", data='{"name":"Testing_1"}', headers=headers) pprint(update.json())
import json import sys import requests if not len(sys.argv) == 2: print("use as 'python check.py [JSON_WEB_TOKEN]'") exit(1) jwt = sys.argv[1] software_list = requests.get('http://localhost:5001/software').json() for sw in software_list: resp = requests.patch( 'http://localhost:5001/software/' + sw['primaryKey']['id'] + '?test=1', json.dumps(sw), headers={ 'Authorization': 'Bearer ' + jwt } ).json() if 'error' in resp: print(sw['primaryKey']['id'] + ': (' + ' -> '.join(map(lambda x: str(x), resp['path'])) + ') ' + resp['error']) else: print(sw['primaryKey']['id'] + ': OK')
def update_service_mapping_plugin(name, files): register_plugin_url = service_mapping_url.format('plugin', 'management', name) return requests.patch(register_plugin_url, files=files, headers=zip_headers)
def testPATCHRequestWithoutCSRFTokenFails(self): response = requests.patch(self.base_url + "/api/hunts/H:123456") self.assertEqual(response.status_code, 403) self.assertIn("CSRF", response.text)
def patch(self, *args, **kwargs) -> Response: kwargs.setdefault('headers', {}) kwargs['headers'] = {**self._headers, **kwargs['headers']} return requests.patch(*args, **kwargs)
def patch(self, url, data, **kwargs): response = requests.patch(self.root + url, data, **kwargs) response = self._response_hook(response=response) return response
def verb_github(verb, url, headers=None, json=None, data=None, status_code=None, json_response=True, token=oauth_token): if isinstance(status_code, int): status_codes = [status_code] else: status_codes = status_code assert verb in verbs, f'{verb} {verbs}' assert implies(verb == 'post' or verb == 'put', json is not None or data is not None) assert implies(verb == 'get', json is None and data is None) if headers is None: headers = {} if 'Authorization' in headers: raise ValueError('Header already has Authorization? ' + str(headers)) headers['Authorization'] = 'token ' + token full_url = f'{GITHUB_API_URL}{url}' if verb == 'get': r = requests.get(full_url, headers=headers, timeout=5) if json_response: output = r.json() if 'Link' in r.headers: assert isinstance(output, list), output link = r.headers['Link'] url = github_link_header_to_maybe_next(link) while url is not None: r = requests.get(url, headers=headers, timeout=5) link = r.headers['Link'] output.extend(r.json()) url = github_link_header_to_maybe_next(link) else: output = r.text else: if verb == 'post': r = requests.post(full_url, headers=headers, data=data, json=json, timeout=5) elif verb == 'put': r = requests.put(full_url, headers=headers, data=data, json=json, timeout=5) elif verb == 'patch': r = requests.patch(full_url, headers=headers, data=data, json=json, timeout=5) if json_response: output = r.json() else: output = r.text if status_codes and r.status_code not in status_codes: raise BadStatus( { 'method': verb, 'endpoint': full_url, 'status_code': { 'actual': r.status_code, 'expected': status_codes }, 'message': 'github error', 'data': data, 'json': json, 'github_json': output }, r.status_code) else: if isinstance(status_code, list): return (output, r.status_code) else: return output
def patch(self, JSON): to_database = json.loads(JSON) requests.patch(url=self.url, json=to_database)
def createFund(fundName, fundDesc, fundGoal, fundCreator): data = '{"'+ fundName +'": {"fundName": "'+ fundName + '", "fundDesc": "'+ fundDesc + '", "fundGoal": "'+fundGoal+'", "fundAmount": "0"}}' id = getUserID(fundCreator) response = requests.patch(BASE_URL + '/userData/' + id + '/funds', headers=headers, data=data) return response
def _updateStatusToPending(self, submissionUrl): r = requests.patch(submissionUrl, data="{\"submissionStatus\" : \"Pending\"}", headers=self.headers)
import requests r = requests.get('https://httpbin.org/get') r = requests.post('https://httpbin.org/post') r = requests.put('https://httpbin.org/put') r = requests.delete('https://httpbin.org/delete') r = requests.patch('https://httpbin.org/patch')
def patch(self, url, patch): r = requests.patch(url, json=patch) r.raise_for_status() return r
"name": "video_name", "likes": 232, "views": 35900 }, { "name": "qwert", "likes": 211132, "views": 13213 }, { "name": "sadasd", "likes": 3213, "views": 5563 }, { "name": "asdad", "likes": 545, "views": 87654 }] for i in range(len(data)): response = requests.put(BASE + "video/" + str(i), data[i]) print(response.json()) # update response = requests.patch(BASE + "video/1", {}) print(response.json()) # get response = requests.get(BASE + "video/1") print(response.json()) # delete response = requests.delete(BASE + "video/2") print(response)
def get_races(eventlist): for race in eventlist: url = race['url'] try: r = requests.get(url) except: time.sleep(3) r = requests.get(url) racelist = [] soup = bs.BeautifulSoup(r.text, 'lxml') for tr in soup.find_all('table'): tds = tr.find_all('td') length = len(tds) for i in range(0, length, 8): #print(tds[i]) #print(tds) x = tds[2 + i].text.strip(' \t\n\r') # print("X = " + x) #print(dir(x)) # x = str(x) #print(type(x)) x = x.replace(" ", "") url = tds[0 + i].find('a') #print(url) url = 'http://www.equibase.com' + url.get('href') tabledic = { 'Race: ': tds[0 + i].text, 'URL': url, 'Purse': tds[1 + i].text, 'Race Type': x, 'Distance': tds[3 + i].text, 'Surface': tds[4 + i].text, 'Starters': tds[5 + i].text, 'Est. Post': tds[6 + i].text, 'Horses': [], } #print(type(tabledic)) racelist.append(tabledic) race['races'] = get_horses(racelist) jsonero = json.dumps(eventlist) jsonic = json.loads(jsonero) print("DATE:", date) #datum o = Country('1', 'America', jsonero, date) #datum o.save() datic = datetime.date.today() d = str(datic) filename = 'USA' + d + '.json' path = "USFiles" fullpath = os.path.join(path, filename) f = open(fullpath, 'w') f.write(jsonero) f.close() p = Podesavanja.objects.get(id=1) p.is_scraping = 0 p.save() headers = {'Authorization': 'Zm9ybXVsYTE='} scaling_payload = { "min": "0", "required": "0", "max": "9", } rer = requests.patch('http://159.65.107.239:8889/api/scaling', json=scaling_payload, headers=headers) print(rer)
def _check_service_template_update(self, data_to_update): # pylint: disable=too-many-locals """Test the service template update :return: None """ # Create the templates (hosts_templates, services_templates) = self._create_templates() # Create an host (host, services) = self._create_host(template_name='linux-nrpe', host_name='nrpe-01') # Find our host template my_host_template = None for tpl in hosts_templates: if tpl['name'] == 'linux-nrpe': my_host_template = tpl break # Find our service template my_template = None for tpl in services_templates: # This template inherits from a linux-nrpe-service template if tpl['name'] == 'linux_nrpe_version': # Get the template from the backend to have a fresh _etag response = requests.get(self.endpoint + '/service/' + tpl['_id'], auth=self.auth) my_template = response.json() break # And find the inherited service my_service = None for service in services: # This template inherits from a linux-nrpe-service template if service['name'] == 'linux_nrpe_version': # Get the service from the backend to have a fresh _etag response = requests.get(self.endpoint + '/service/' + service['_id'], auth=self.auth) my_service = response.json() break if data_to_update is None: data_to_update = {} for prop in my_template: # Exclude Python-Eve specific fields if prop in ['_created', '_updated', '_links', '_etag', '_id']: continue # Exclude some not -logicial to update fields if prop in ['host']: continue # if prop in ['_is_template']: data_to_update.update({prop: my_template.get(prop)}) print("Data to update: %s" % data_to_update) # Update the service element headers = { 'Content-Type': 'application/json', 'If-Match': my_template['_etag'] } response = requests.patch(self.endpoint + '/service/' + my_template['_id'], json=data_to_update, headers=headers, auth=self.auth) # Get the services from the backend to confirm the impacts params = {'where': json.dumps({'name': 'linux_nrpe_version'})} response = requests.get(self.endpoint + '/service', params=params, auth=self.auth) items = response.json() # There are 2 services named as 'linux_nrpe_version' assert len(items['_items']) == 2 services = items['_items'] for service in services: if service['_is_template']: # The template one is the template we updated # Compare after update - except for some specific fields... my_template['_etag'] = service['_etag'] my_template['_updated'] = service['_updated'] my_template['_links'] = service['_links'] # ... and for the modified field! for prop in data_to_update: my_template[prop] = service[prop] self.assertEqual(my_template, service) # Service template is still related to its host template self.assertEqual(service['host'], my_host_template['_id']) else: # The not template one is the service inherited on host creation # Compare after update - except for some specific fields... my_service['_etag'] = service['_etag'] my_service['_updated'] = service['_updated'] my_service['_links'] = service['_links'] # ... and for the modified field! for prop in data_to_update: my_service[prop] = service[prop] self.assertEqual(my_service, service) # Service is still related to its host self.assertEqual(service['host'], host['_id']) # Get the inherited host from the backend to confirm it did not changed response = requests.get(self.endpoint + '/host/' + host['_id'], auth=self.auth) my_new_host = response.json() # Compare after update - except for some specific fields... host['_etag'] = my_new_host['_etag'] host['_updated'] = my_new_host['_updated'] host['_links'] = my_new_host['_links'] self.assertEqual(host, my_new_host)
def update(self, url, etag, changes, entity=None, headers=None): r = requests.patch(url, json=changes, headers=headers if headers is not None else self.update_headers(etag)) return self.process_resource_result(url, r, entity)
def post_request(state): body = {'state': '{}'.format(state)} url = 'http://localhost:3000/muses/1' r = requests.patch(url, data=body)
print(headers) # Ascend usage update boady # body = { # "Date__c": "2019-10-01", # "ConnectionsSum__c": 19029, # "ImpressionsSum__c": 67890, # # "AccountID__c":"0011s000007ZA3cAAG", # "AccountID__c": "123sasdasdw9090iGH", # "UniqueLabel__c": "0011s000007ZA3cAAG 2019-11-02" # } # Provision status update body body = { "Provisioning_status__c": "Active", } response = requests.patch(url, headers=headers, data=json.dumps(body)) print(response.status_code) print(response.content) # url=host_url+'/services/data/v47.0/query/?q=%s' # # if response.status_code==400: # print("Replace") # res=json.loads(response.content)[0] # record_id=res.get("message").split(" ")[-1] # print(record_id) # # url = host_url + "/services/data/v32.0/sobjects/Usageb__c/"+record_id # body={ # "ConnectionsSum__c":19029, # "ImpressionsSum__c":67890,