def send_message(): print(request.form.get('tarea')) mensaje = { "queue": "myqueue", "message": request.form.get('tarea') } request.post("ip del middleware", mensaje) #mandar esto al middleware return "sending message"
def announce_new_block(block): # A function to announce to the network once a block has been mined. # Other blocks can simply verify the proof of work and add it to their # respective chains. for peer in peers: url = "{}add_block".format(peer) headers = {'Content-Type': "application/json"} request.post(url, data=json.dumps(block.__dict__, sort_keys=True), headers=headers)
def dump(): paths = request.get_json()['paths'] print for i, path in enumerate(paths): book_info = requests.get("http://localhost:8080/api/v1/books/"+ str(i+1)).json() to_elastic = [i,book_info['author'],book_info['price'],book_info['imageUrl'],book_info['title']] temp_res = get_all_statistics(path) # ganre, pers, loc, summurize for processed_data in temp_res: to_elastic.append(processed_data); request.post("http://localhost:5000/save", json={"data": to_elastic })
def broadcast_transaction(transaction): not_sent = True data = pickle.dumps(transaction, protocol=2) while not_sent: try: request.post("http://" + args.ip_other + "/transaction", data=data) not_sent = False except: time.sleep(0.1) return True
def create_product(): print('f**k off') product_url = basee_url.format(itemId=request.args['itemId'], API_KEY=API_KEY) print(product_url) resp = request.post(product_url, data={ 'itemId': request.args['itemId'] }).json() print('after product call') count_rows = session.execute("SELECT COUNT(*) FROM smartcart.products") for c in count_rows: last_id = c.count last_id += 1 print(request.form['name']) # print(request.args) resp = session.execute( "INSERT INTO smartcart.product(itemId,description,id,name,price) VALUES(%s, %s, %s, %s, %s)", (request.form['itemId'], request.form['shortDescription'], last_id, request.form['name'], request.form['salePrice'])) print('done') return jsonify({'message': 'added'}), 201
def runUdpReceiver(self): while True: data, addr = self.server.recvfrom(1024) dataJson = json.loads(data) if (dataJson["coin"] == "simplecoin"): # address = "http://" + addr[0] + ":"+ str(addr[1]) # Address of ledger on other client should be on port 8001 address = "http://" + addr[0] + ":" + str(8001) tosend = dict() tosend['ip'] = socket.gethostbyname(socket.gethostname()) tosend['encryptedNonce'] = encryptedNonce tosend['wallet'] = Wallet("new Name", creatorKey, "") # At this point I have sent a post request and am saving the response which is a list of all known peers and # an ecrypted nonce, and a public key r = request.post(url=address + "/peers", data=tosend) postResponse = r.getresponse() if (postResponse.text == ""): print("already registered with other peer") else: postData = postResponse.read() alldata = JSON.parse(postData) encryptedNonced = alldata['encryptedNonce'] publicKey = alldata['publicKey'] decryptedNonced = rsa.decryptMessage( publicKey, encryptedNonced) if (decryptedNonced == nonce): currPeerList = ledger.getPeerList() newPostPeers = alldata['peerList'] util.joinPeerLists(newPostPeers, currPeerList)
def dentist(): url2 = 'https://dev.virtualearth.net/REST/v1/LocalSearch/?query=%s&userLocation=%s,%s&key=' % ( 'dentist', '47.602038', '-122.333964') #print(url) re2 = request.get(url2) returning2 = json.loads(re2.text) #return returning['resourceSets']['0']['estimatedTotal'] #print(type(returning['resourceSets'][0]['resources'])) #print(returning[f 'resourceSets'][0]['resources'][0]['point']['coordinates']) Dict2 = {} for i in range(len(returning2['resourceSets'][0]['resources']) - 1): Result_name2 = returning2['resourceSets'][0]['resources'][i]['name'] Result_coordinates2 = returning2['resourceSets'][0]['resources'][i][ 'point']['coordinates'] print(Result_name2) Dict2[str(i)] = [Result_name2, Result_coordinates2] #47.602038,-122.333964 returnFile = json.dumps(Dict) payload = returnFile r = request.post( 'https://www.jsonstore.io/71fc6d609168087b1bd76dea68e7694b4f451bfa7bf7ab5ebb4717dd15bb65d8', json=payload) return json.dumps(Dict2)
def main(): if request.method == 'POST': email = Email(email=request.post('email')) db.session.add(email) db.session.commit() return 'ok' return render_template('index.html')
def triggerAlert(patientID, patientName): eobs = requests.get(f'{BASE_URL}ExplanationOfBenefit', headers=getAuth()) eobList = eob.json() practitionerID = "" for eob in eobList["entry"]: if patientID in eob["patient"]["reference"]: if practitionerID != "": practitionerID = eob["provider"]["reference"].split(':')[-1] practitioner = requests.get(f'{BASE_URL}Practitioner/{practitionerID}', headers=getAuth()) practitioner = practitioner.json() practitionerName = practitioner["name"][0]["prefix"][0] + ' ' + practitoiner["name"][0]["given"][0] + ' ' + practitioner["name"][0]["family"] email = practitioner["telecom"][0]["value"] headers = { "Content-Type": "application/json" } body = { "patientName": patientName, "patientID": patientID, "practitionerEmail": email, "practitionerName": practitionerName } r = request.post("https://prod-12.northcentralus.logic.azure.com:443/workflows/62a70a0642614461b3ec9c2767ee9236/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=XfeJAedegM-_xuZO42gleTI3wxojaxmXYsxEKZphp0E", json=body, headers=headers) return True
def register_with_existing_node(): # Internally calls the 'register_node' endpoint to # register current node with the remote node specified in the # request, and sync the blockchain as well with the remote node. node_address = request.get_json()["node_address"] if not node_address: return "Invalid data", 400 data = {"node_address": request.host_url} headers = {'Content-Type': "application/json"} # Make a request to register with remote node and obtain information response = request.post(node_address + "/register_node", data=json.dumps(data), headers=headers) if response.status_code == 200: global blockchain global peers # update chain and the peers chain_dump = response.json()['chain'] blockchain = create_chain_from_dump(chain_dump) peers.update(response.json()['peers']) return "Registration successful", 200 else: # if something goes wrong, pass it on to the API response return response.content, response.status_code
def cisco(): headers = { 'X-Cisco-Meraki-API-Key': '', } re = request.get( 'https://api.meraki.com/api/v0/devices/Q2GV-XLK8-MDBK/camera/analytics/recent', headers=headers) returning = json.loads(re.text) print(round(returning[0]['averageCount'] * 200, 2)) payload = str(round(returning[0]['averageCount'] * 200, 2)) yeet = request.post( 'https://www.jsonstore.io/039e0e4f386c305904fa8f4ff8b2f4953466ffb2537854a943978dba2fa3336e', json=payload) account_sid = 'ACdbe67a5dd0793ed622caea1b81519704' auth_token = 'fe1e53e4b7259b5c60b2ec7780b9d4b4' client = Client(account_sid, auth_token) timeMinutes = payload doctorNumber = '+16475265284' call = client.calls.create( url= 'http://twimlets.com/echo?Twiml=%3C%3Fxml%20version%3D%221.0%22%20encoding%3D%22UTF-8%22%3F%3E%0A%3CResponse%3E%0A%20%20%20%20%3CSay%20voice%20%3D%20%22alice%22%3EHello%20I%20represent%20a%20Destination%20Doc%20patient.%20I%20am%20on%20my%20way%20to%20your%20location%2C%20please%20book%20an%20appointment%20for%20earliest%20' + timeMinutes + '%20minutes.%20Thank%20you.%3C%2FSay%3E%0A%3C%2FResponse%3E&', to=doctorNumber, from_='+14388004097') print(call.sid) return str(returning[0]['averageCount'] * 20)
def client(proxy_host): sse = requests.get(proxy_host + '/register', stream=True) for line in sse.iter_lines(): assert line == 'data: rts\r\n' mjpeg = FFmpeg('-i', '/dev/video0', '-f', 'mp4', '-c:v', 'hevc', 'pipe:') r = request.post(proxy_host + '/upload', data=mjpeg.stdout)
def submit_textarea(): """ Endpoint to create a new transaction via our application """ post_content = request.form["content"] author = request.form["author"] post_object = {'author': author, 'content': post_content} # Submit a tx new_tx_address = f"{CONNECTED_NODE_ADDRESS}/new_transaction" request.post(new_tx_address, json=post_object, headers={'Content-type': 'application/json'}) # return to homepage return redirect('/')
def broadcast_new_block(self, block): neighbors = self.nodes post_data = {'block': block} for node in neighbors: response = request.post(f'http://{node}/block/new', json=post_data) if response.status_code != 200: print('Error broadcasting new block') pass
def already_sent(form): resp = request.post(URL + "/messages", auth=('api', KEY), data={ "to": form.get('From'), "from": our_email, "subject": "Failed to deliver", "text":"You already sent us an email for the day", })
def chat(): book_id = request.get_json()['id'] question = request.get_json()['qestion'] elastic_data = requests.post("http://localhost:5000/get_by_id" , json={ "query" : book_id}).json() resp = request.post("http://localhost:5000/model",json={ "context_raw": [elastic_data['summirize']], "question_raw": question}).json() return resp[0][0]
def broadcast_new_block(self, new_block): neighbors = self.nodes post_data = {'block': new_block} for node in neighbors: response = request.post(f'http://{node}/block/new', json=post_data) if response.status_code != 200: # Error handling pass
def helloworld(): content = request.get_json() name= content["Name"] temp={} temp["My_name"]=name # Send this data to PUT aPI r=request.post(url="http://127.0.0.1:5000/", data=temp) resp=r.text print(resp) return "Hello"+ name
def image(url): img = requests.get(url) f = {'file': img.content} return request.post( 'https://dialogs.yandex.net/api/v1/skills/443fbd7b-d880-4de9-871a-810a740e87eb/images', files=f, headers={ 'Authorization': 'OAuth AQAAAAAgQEMJAAT7o1ZMa7CzxUDzt4G2NF-GyJA', 'Content - Type': 'multipart/ form - data' }).json()['image']['id']
def get_piece(hash): #envoie du hash au back de la marketplace url = "httpS://ethparis.herokuapp.com/piece_from_hash" data = {"hash": hash} response = request.post( url, json=data, ).text #return la pièce return flask.jsonify(response)
def broadcast_message(message, uid): succeed = 0 for p in peers: r = request.post(contruct_url(p, '/message'), json={ 'message': message, 'uid': uid }) if r.status_code == 200: succeed += 1 return 0 if len(peers) == 0 else succeed * 1.0 / len(peers)
def demoFunction(self): json_data = { "title": "test title", "description": "test description", "targetDate": "2010/09/09", "clientPriority": 3, "selectClient": 2, "productArea": 2 } resp = request.post("http://127.0.0.1:5000/index", json=json_data) resp = resp.json() self.assertTrue(resp['success'])
def webcam(): result, file_name = Wp.outputPicture() #result = Ws.outputScreen() #파일명 출력 print(file_name) #서버 url url = '' #파일 열기 files = {'file': open(file_name, 'rb')} r = request.post(url, files=files) r.text return result
def broadcast_new_block(self, block): """ alert neighbors in list of nodes that a new block has been mined and added to the chain """ post_data = {"block": block} for node in self.nodes: r = request.post(f'http://{node}/block/new', json=post_data) if response.status_code != 200: #TODO pass
def study_image(): image_url = request.form['url-input'] # At this point you have the image_url value from the front end # Your job now is to send this information to the Clarifai API # and read the result, make sure that you read and understand the # example we covered in the slides! # YOUR CODE HERE! #import request, json headers = {'Authorization':'Key f2f339a3cc374420a221fa27e58a3202'} api_url="https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs" data ={"inputs": [{"data": {"image": {"url": "https://samples.clarifai.com/metro-north.jpg"}}}]} response = request.post(api_url, headers=headers,data=json.dumps(data))
def broadcast_new_block(self, block): """ Alert neighbors in list of nodes that a new block has been mined. :param block: <Block> the block that has been mined and added to the chain """ post_data = {"block": block} for node in self.nodes: response = request.post(url=f"http://{node}/block/new", json=post_data) if response.status_code != 200: # TODO: Error Handling pass
def search(): query = request.args.get('q') tweets = g.user.twitter_request( 'https://api.twitter.com/1.1/search/tweets.json?q={}'.format(query)) tweet_texts = [{ 'tweet': tweet['text'], 'label': 'neutral' } for tweet in tweets['statuses']] for tweet in tweet_texts: r = request.post('http://text-processing.com/api/sentiment/', data={'tweet': tweet['tweet']}) json_response = r.json() label = json_response['label'] tweet['label'] = label return render_template('search.html', content=tweet_texts)
def study_image(): image_url = request.form['url-input'] headers = {'Authorixation': 'key < 3ec5e4ff7f814f37a5351e44c4c38685>'} api_url = "https://api.clarifai.com/v2/models/aaa03c23b3724a16a56b629203edc62c/outputs" data = {"inputs": [{"data": {"image": {"url": 'image_url'}}}]} response = request.post(api_url, headers=headers, data=jason.dumps(data)) # At this point you have the image_url value from the front end # Your job now is to send this information to the Clarifai API # and read the result, make sure that you read and understand the # example we covered in the slides! # YOUR CODE HERE! return render_template('home.html', results=response)
def register(): req_data = request.json() print(req_data) hostname = req_data['hostname'] ip = req_data['ip'] as_ip = req_data['as_ip'] as_port = req_data['as_port'] url = "http://" + as_ip + ":" + as_port + "/registerdns" data = { "TYPE": "A", "NAME": hostname, "VALUE": ip, "TTL": 10, } data_json = json.dumps(data) r = request.post(url, data_json) return r
def apicustomer(): try: if request.method == "POST": data = request.get_json() payload = { "customer": { "first_name": data["first_name"], "last_name": data["last_name"], "email": data["email"], "phone": data.get("phone") } } url = sk.STORE_DOMAIN + f"admin/api/2020-10/customers.json" result = request.post(url, auth=(sk.API_KEY, sk.API_PASSWORD), json=payload) if result.ok: return result.json(), 201 else: return result.json(), 403 elif request.method == "PUT": data = request.get_json() url = sk.STORE_DOMAIN + f"admin/api/2020-10/customers/{data['customer_id']}.json" payload = { "customer": { "id": data['customer_id'], "first_name": data.get("first_name"), "last_name": data.get("last_name"), "email": data.get("email"), "phone": data.get("phone"), "tags": data.get("tags") } } result = requests.put(url, auth=(sk.API_KEY, sk.API_PASSWORD), json=payload) if result.ok: return result.json(), 201 else: return result.json(), 403 except Exception as err: return jsonify({"error": repr(err)}), 403
def searchMerchant(): cert_file_path = "cert.pem" key_file_path = "key.pem" cert = (cert_file_path,key_file_path) body = request.json visaMerchantId = request.json['visaMerchantId'] visaStoreId = request.json['visaStoreId'] visaMerchantId = request.json['visaMerchantId'] visaStoreId = request.json['visaStoreId'] payload={ "searchAttrList": { "visaMerchantId": visaMerchantId, "visaStoreId": visaStoreId, "merchantCountryCode": "840" }, "responseAttrList": [ "GNSTANDARD" ], "searchOptions": { "wildCard": [ "merchantName" ], "maxRecords": "5", "matchIndicators": "true", "matchScore": "true", "proximity": [ "merchantName" ] }, "header": { "requestMessageId": "Request_001", "startIndex": "0", "messageDateTime": "2020-06-30T13:29:03.903" } } url = "https://sandbox.api.visa.com/merchantsearch/v1/search" headers={ "Content-Type":"application/json", "Authorization": "Basic UUdYMjAyOEM5UjBJNkJTQlZXRTMyMVpKRFRjczkyRkxCWFlpR1ZkUUxHTmRIQndXODpFVDRxMk5xcHpQVG5ObG9tcjR0dg==" } response = request.post(url, data = payload, header, cert = cert, verify = "DigiCertGlobalRootCA.crt")
def create_qemu_vm(name, vmid, cores, memory, disksize, network, ipaddr, sshkey): checksession() url = proxmoxurl + '/' builddoc = { "name": str(name), "vmid": int(vmid), "cores": int(cores), "memory": int(memory * 1024), "disksize": str(disksize + 'G'), "network": int(network), "ipaddr": str(ipaddr), "sshkeyloc": str(sshkey) } r = request.post(url, data=builddoc) if r.status == 200: return '{"success": True}' else: return '{"success": False}'
def access_token(self): """ :return: """ data = { 'client_id': self.client_id, 'client_secret': self.client_secret, 'scope': 'http://api.microsofttranslator.com', 'grant_type': 'client_credentials' } r = request.post( 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/', data=data) result = json.loads(r.text) if 'error_description' in result: raise AuthenticationFailed(result['access_token']) else: self.access_token = result['access_token'] self.time = time.time()