Пример #1
0
    def post(self, uri, payload=None, etag=None,
             content_type="application/json", accept="application/json"):

        headers = {'content-type': content_type,
                   'accept': accept}
        if etag is not None:
            headers['if-match'] = etag

        self.logger.debug("POST {0}...".format(uri))
        self.payload_logger.debug("Headers:")
        self.payload_logger.debug(json.dumps(headers, indent=2))
        if payload != None:
            self.payload_logger.debug("Payload:")
            if content_type == 'application/json':
                self.payload_logger.debug(json.dumps(payload, indent=2))
            else:
                self.payload_logger.debug(payload)

        if payload is None:
            self.response = requests.post(uri, auth=self.auth, headers=headers)
        else:
            if content_type == "application/json":
                self.response = requests.post(uri, json=payload,
                                              auth=self.auth, headers=headers)
            else:
                self.response = requests.post(uri, data=payload,
                                              auth=self.auth, headers=headers)

        return self._response()
Пример #2
0
def deferred_add_user_to_album(album_url, user_id, response_url=None):
    response = {
        'attachments': build_my_list_attachment(),
        'replace_original': False,
        'response_type': 'ephemeral',
        'text': 'Added album to your list.',
    }
    try:
        album = albums_model.get_album_details_by_url(album_url)
        if album:
            albums_model.add_user_to_album(album.album_id, user_id)
        else:
            deferred_consume.delay(
                album_url,
                bandcamp.scrape_bandcamp_album_ids_from_url_forced,
                list_model.add_to_list,
                response_url=response_url,
            )
            deferred_add_user_to_album.delay(album_url, user_id, response_url=response_url)
            return
        flask.current_app.cache.delete(f'u-{user_id}')
    except DatabaseError as e:
        response['text'] = 'Failed to add album to your list.'
        print(f'[db]: failed to add user to album')
        print(f'[db]: {e}')
    else:
        print(f'[db]: added user to album')
    if response_url:
        requests.post(response_url, data=json.dumps(response))
Пример #3
0
def process_action(request, server_id):
    if not request.POST:
        return HttpResponseNotAllowed(['POST'])
    action = request.POST['action']
    process_name = request.POST['process']
    server = Server.objects.get(id=server_id)
    process = server.process_set.get(name=process_name)
    ip_address = server.address
    time_out = 15
    try:
        # would only work for this server
        # subprocess.call(["monit", action, process_name])

        monit_url = 'http://%s:%s@%s:%s/%s' % (monit_user, monit_password, ip_address, monit_port, process_name)
        requests.post(monit_url, {'action': action}, timeout=time_out)
        action_labels = {'start': 'starting...', 'stop': 'stopping...', 'restart': 'restarting...', 'unmonitor': 'disable monitoring...', 'monitor': 'enable monitoring...'}
        if action in action_labels:
            process.status = action_labels.get(action)
            if action == 'unmonitor':
                process.monitor = 0
            elif action == 'monitor':
                process.monitor = 2
            process.save()
        return redirect(reverse('monitcollector.views.process', kwargs={'server_id': server.id, 'process_name': process_name}))
    except:
        return render(request, 'monitcollector/error.html', {'time_out': time_out, 'monit_user': monit_user, 'ip_address': ip_address, 'monit_port': monit_port, 'process_name': process_name})
Пример #4
0
    def worker(self):
        if not ENDPOINT:
            return
        while True:
            datapack = {'sensors': {}}

            for sensor in Sensor.get_all():
                data = {}
                for variant in sensor.get_variants():
                    data[variant] = sensor.value(variant)
                datapack['sensors'][sensor.id] = data

            gevent.sleep(3)
            url = ENDPOINT % ajenti.config.tree.installation_id

            if not self.get_key():
                continue

            try:
                requests.post(url, data={
                    'data': json.dumps(datapack),
                    'key': self.get_key()
                })
                self.last_report = datetime.now()
                self.last_error = None
            except Exception, e:
                self.last_error = e
Пример #5
0
    def test_api_fire_event_with_invalid_json(self):
        """Test if the API allows us to fire an event."""
        test_value = []

        def listener(event):
            """Helper method that will verify our event got called."""
            test_value.append(1)

        hass.bus.listen_once("test_event_bad_data", listener)

        req = requests.post(
            _url(const.URL_API_EVENTS_EVENT.format("test_event_bad_data")),
            data=json.dumps('not an object'),
            headers=HA_HEADERS)

        hass.pool.block_till_done()

        self.assertEqual(400, req.status_code)
        self.assertEqual(0, len(test_value))

        # Try now with valid but unusable JSON
        req = requests.post(
            _url(const.URL_API_EVENTS_EVENT.format("test_event_bad_data")),
            data=json.dumps([1, 2, 3]),
            headers=HA_HEADERS)

        hass.pool.block_till_done()

        self.assertEqual(400, req.status_code)
        self.assertEqual(0, len(test_value))
Пример #6
0
 def setup_oauth(self):
     # Request token
     oauth = OAuth1(CONSUMER_KEY, client_secret=CONSUMER_SECRET)
     r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)
     credentials = parse_qs(r.content)
     
     resource_owner_key = credentials.get('oauth_token')[0]
     resource_owner_secret = credentials.get('oauth_token_secret')[0]
     
     # Authorize
     authorize_url = AUTHORIZE_URL + resource_owner_key
     print 'Please go here and authorize: ' + authorize_url
     
     verifier = raw_input('Please input the verifier: ')
     oauth = OAuth1(CONSUMER_KEY,
                    client_secret=CONSUMER_SECRET,
                    resource_owner_key=resource_owner_key,
                    resource_owner_secret=resource_owner_secret,
                    verifier=verifier)
     
     # Finally, Obtain the Access Token
     r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)
     credentials = parse_qs(r.content)
     token = credentials.get('oauth_token')[0]
     secret = credentials.get('oauth_token_secret')[0]
     
     return token, secret
Пример #7
0
def test_Anrufer_sperren_in_web():
    u = inte_testutils.TestUtil()
    u.unblock_callerid(TelephoneNumber('0790000003'))

    assert not u.is_blocked_callerid(TelephoneNumber('0790000003'))
    requests.post('http://localhost/block_caller', data={'telephone_number': '0790000003'})
    assert u.is_blocked_callerid(TelephoneNumber('0790000003'))
Пример #8
0
def get_access_keys():
    
    #Request Token
    app_oauth = OAuth1(keys.CONSUMER_KEY, client_secret = keys.CONSUMER_SECRET)
    authorize_data = requests.post(url = REQUEST_TOKEN_URL, auth = app_oauth)
    authorize_credentials = parse_qs(authorize_data.content);
    authorize_key = authorize_credentials.get('oauth_token')[0]
    authorize_secret = authorize_credentials.get('oauth_token_secret')[0]

    #Authorize Token
    authorization_url = AUTHORIZE_BASE_URL + authorize_key
    print 'Authorize this application at: ' + authorization_url
    verify_pin = raw_input('Enter your verification pin: ')

    #Obtain Access Token
    access_token = OAuth1(keys.CONSUMER_KEY,
                          client_secret = keys.CONSUMER_SECRET,
                          resource_owner_key = authorize_key,
                          resource_owner_secret = authorize_secret,
                          verifier = verify_pin)
    access_data = requests.post(url = ACCESS_TOKEN_URL, auth = access_token)
    print access_data
    #Need to add error code handling
    if access_data.status_code == 200:
        access_credentials = parse_qs(access_data.content)
        access_token = access_credentials.get('oauth_token')[0]
        access_secret = access_credentials.get('oauth_token_secret')[0]
        print 'Add the following to plat/apikeys/twitter_keys.py:'
        print "ACCESS_KEY = '" + access_token + "'"
        print "ACCESS_SECRET = '" + access_secret + "'"
        exit()
    else:
        print 'Some sort of error'
        exit()
Пример #9
0
 def merge_kitchens_improved(self, from_kitchen, to_kitchen, resolved_conflicts=None):
     """
     merges kitchens
     '/v2/kitchen/merge/<string:kitchenname>/<string:kitchenname>', methods=['POST']
     :param resolved_conflicts:
     :param self: DKCloudAPI
     :param from_kitchen: string
     :param to_kitchen: string
     :rtype: dict
     """
     rc = DKReturnCode()
     if from_kitchen is None or isinstance(from_kitchen, basestring) is False:
         rc.set(rc.DK_FAIL, 'issue with from kitchen')
         return rc
     if to_kitchen is None or isinstance(to_kitchen, basestring) is False:
         rc.set(rc.DK_FAIL, 'issue with to kitchen')
         return rc
     url = '%s/v2/kitchen/merge/%s/%s' % (self.get_url_for_direct_rest_call(), from_kitchen, to_kitchen)
     try:
         if resolved_conflicts is not None and len(resolved_conflicts) > 0:
             data = dict()
             data['resolved_conflicts'] = resolved_conflicts
             response = requests.post(url, data=json.dumps(data), headers=self._get_common_headers())
         else:
             response = requests.post(url, headers=self._get_common_headers())
         rdict = self._get_json(response)
     except (RequestException, ValueError, TypeError), c:
         rc.set("merge_kitchens: exception: %s" % str(c))
         return rc
    def test_06_create_transaction_1(self):
        # Create transaction
        params = {'value': 1100}
        r = requests.post(''.join((URL + ('user', '/', self.user, '/', 'transaction', '/'))),
                          headers=HEADERS,
                          data=json.dumps(params))
        now = datetime.datetime.utcnow()
        self.assertEqual(201, r.status_code)
        self.assertEqual('application/json', r.headers['Content-Type'])
        result = json.loads(r.text)
        self.assertTrue({'id', 'user', 'create_date', 'value'}.issubset(result), msg=str(result))
        self.assertEqual(self.user, str(result['user']))
        self.assertEqual(1100, result['value'])
        # TODO This assumes Z timezone a.k.a. UTC. Should be handled and parsed properly
        create_date = datetime.datetime.strptime(result['create_date'], '%Y-%m-%dT%H:%M:%S.%fZ')
        self.assertGreater(20, (now - create_date).total_seconds())

        params = {'value': 1201}
        r = requests.post(''.join((URL + ('user', '/', self.user, '/', 'transaction', '/'))),
                          headers=HEADERS,
                          data=json.dumps(params))
        now = datetime.datetime.utcnow()
        self.assertEqual(201, r.status_code)
        self.assertEqual('application/json', r.headers['Content-Type'])
        result = json.loads(r.text)
        self.assertTrue({'id', 'user', 'create_date', 'value'}.issubset(result), msg=str(result))
        self.assertEqual(self.user, str(result['user']))
        self.assertEqual(1201, result['value'])
        # TODO This assumes Z timezone a.k.a. UTC. Should be handled and parsed properly
        create_date = datetime.datetime.strptime(result['create_date'], '%Y-%m-%dT%H:%M:%S.%fZ')
        self.assertGreater(20, (now - create_date).total_seconds())
        self.assert_user(self.user, (1100, 1201))
Пример #11
0
    def csv_upload(self, filename, operation):
        # create the request url for init.
        rest_url_pre = 'https://' + self.iba_host + '/wapi/v' + self.iba_wapi_version

        try:
            init_url = rest_url_pre + '/fileop?_function=uploadinit'
            # send request to the server to establish the object, with token and url.
            r = requests.post(url=init_url, auth=(self.iba_user, self.iba_password), verify=self.iba_verify_ssl)
            r_json = r.json()

            # need to do escaping or we will have issues when it's sent to the requests.post
            token = r_json['token'].encode('unicode-escape')
            req_url = r_json['url']
            files = {'file': (filename, open(filename, 'rb')) }
            file_r = requests.post(url=req_url, auth=(self.iba_user, self.iba_password), verify=self.iba_verify_ssl, files=files)

            # Use the token to tell the server to process the file as a csv_import
            csv_url = rest_url_pre + '/fileop?_function=csv_import'
            payload = '{ "token": "' + token + '", "operation": "' + operation + '" }'
            requests.post(url=csv_url, auth=(self.iba_user, self.iba_password), verify=self.iba_verify_ssl, data=payload)

        except ValueError:
            raise Exception(r)
        except Exception:
            raise
Пример #12
0
    def _authenticate(self, response=None, headers=None):
        if self._authn_type is None:
            return headers
        url = "%s://%s:%s%s" % (self._authn_protocol, self._authn_server, self._authn_port,
                                  self._authn_url)
        new_headers = headers or {}
        try:
           if self._ksinsecure:
                response = requests.post(url, data=self._authn_body,
                                     headers=self._DEFAULT_AUTHN_HEADERS, verify=False)
           elif not self._ksinsecure and self._use_ks_certs:
                response = requests.post(url, data=self._authn_body,
                                         headers=self._DEFAULT_AUTHN_HEADERS, verify=self._kscertbundle)
           else:
                response = requests.post(url, data=self._authn_body,
                                         headers=self._DEFAULT_AUTHN_HEADERS)
        except Exception as e:
            errmsg = 'Unable to connect to keystone for authentication. '
            errmsg += 'Exception %s' %(e)
            raise RuntimeError(errmsg)

        if (response.status_code == 200) or (response.status_code == 201):
            # plan is to re-issue original request with new token
            if 'v2' in self._authn_url:
                authn_content = json.loads(response.text)
                self._auth_token = authn_content['access']['token']['id']
            else:
                self._auth_token = response.headers['x-subject-token']
            new_headers['X-AUTH-TOKEN'] = self._auth_token
            return new_headers
        else:
            raise RuntimeError('Authentication Failure')
Пример #13
0
	def post_to_slack(self, file_name, file_content, bot_callback=None, title=None):
		slack = getSecrets('slack')

		data = {
			'token' : slack['api_token'],
			'title' : "i deepdreamed..." if title is None else title,
			'channels' : slack['channel_id']
		}

		try:
			r = requests.post("https://slack.com/api/files.upload", data=data, files={ 'file' : file_content})
			res = json.loads(r.content)

			if not res['ok']:
				return False

			if bot_callback is not None:
				r = requests.post(slack['webhook_url'], data={'payload' : json.dumps({ 'text' : bot_callback })})
				print r.content

			return True

		except Exception as e:
			print e, type(e)

		return False
Пример #14
0
def bale_CRITs_indicator(base_url, data, indicator_que):
    """ One thread of adding indicators to CRITs"""
    while not indicator_que.empty():
        indicator = indicator_que.get()
        if indicator[1] == 'IPv4':
            # using the IP API
            url = base_url + 'ips/'
            data['add_indicator'] = "true"
            data['ip'] = indicator[0]
            data['ip_type'] = 'Address - ipv4-addr'
            data['reference'] = indicator[3]
            # getting the source automatically:
            source = re.findall(r'\/\/(.*?)\/', data['reference'])
            if source:
                data['source'] = source[0]
            res = requests.post(url, data=data, verify=False)
            if not res.status_code in [201, 200, 400]:
                logger.info("Issues with adding: %s" % data['ip'])
        elif indicator[1] == "FQDN":
            # using the Domain API
            url = base_url + 'domains/'
            data['add_indicator'] = "true"
            data['domain'] = indicator[0]
            data['reference'] = indicator[3]
            # getting the source automatically:
            source = re.findall(r'\/\/(.*?)\/', data['reference'])
            if source:
                data['source'] = source[0]
            res = requests.post(url, data=data, verify=False)
            if not res.status_code in [201, 200, 400]:
                logger.info("Issues with adding: %s" % data['domain'])
        else:
            logger.info("don't yet know what to do with: %s[%s]" % (indicator[1], indicator[0]))
Пример #15
0
    def upload(self, path):
        """
        Uploads a file to the current folder. Takes a file location as an
        argument, either relative or absolute. If a file of the same name is
        already in the current folder, a new version is uploaded.

        Returns True if file upload is successful, False otherwise.
        """
        parent_id = self.current_folder.get('id')
        item_id = None
        filename = path.split('/')[-1]
        for entry in self.current_folder.get('item_collection').get('entries'):
            if (entry.get('name') == filename and entry.get('type') == 'file'):
                item_id = entry.get('id')
                break
        if (item_id == None):
            f = requests.post('https://upload.box.com/api/2.0/files/content', 
                headers = { 'Authorization': 'Bearer ' + self.token }, 
                data = { 'filename': filename, 'parent_id':parent_id }, 
                files = { filename: open(path, 'rb')})
        else:
            f = requests.post('https://upload.box.com/api/2.0/files/' + 
                item_id + '/content', headers = { 'Authorization': 'Bearer ' + 
                self.token }, data = { 'filename': filename }, files = { 
                filename: open(path, 'rb')})
        if (f.status_code == 409):
            print "File upload caused a conflict"
            return False
        elif (f.status_code != 201):
            print "Problem uploading the file"
            return False
        else:
            print "File uploaded"
            return True
Пример #16
0
def addtrade(request):
    """
    API interface: Request handler for adding a new trade to :model:`hw1.Trades`.

    Required parameters:

        1. First name of the trader
        2. Last name of the trader
        3. Company the trader belongs to

    """
    date_time=time.strftime('%Y-%m-%d %H:%M:%S')
    product=request.POST.get('product', False)
    month=request.POST.get('month', False)
    year=request.POST.get('year', False)
    lots=request.POST.get('lots', False)
    price=request.POST.get('price', False)
    sign=''
    if request.POST.get('sign', False) == 'Buy':
        sign=1
    else:
        sign=-1
    trader= Clients.objects.get(id=request.POST.get('trader', False))
    side = request.POST.get('sign', False).lower();
    type = request.POST.get('type', False)
    post_data = {'type': type, 'side': side, 'symbol': product, 'price': price, 'lots' : lots}
    new = Trades(status = 0, time = date_time, product_code = product, month_code = month, year = year, lots = lots, price = price, buy_or_sell = sign, trader = trader)
    id = Trades.objects.latest('id')
    post_data = {'id': id, 'type': type, 'side': side, 'symbol': product, 'price': price, 'lots' : lots}
    requests.post('localhost:8080/fix/process-order', data=post_data)
    new.save()
    return HttpResponseRedirect('/hw1/?success=true')
Пример #17
0
def getTrackIDs(performer):
	r = requests.post('http://muzis.ru/api/search.api', data = {'q_performer':performer})
	artId = json.loads(r.text)["performers"][0]["id"]
	r = requests.post('http://muzis.ru/api/get_songs_by_performer.api', data = {'performer_id':artId,'type':'3'})
	listOfSongs = json.loads(r.text)['songs']
	#a = [x["file_mp3"] for x in listOfSongs]
	return(listOfSongs[:5])	
Пример #18
0
def worker(worker_info, password, remote):
  global ALIVE

  payload = {
    'worker_info': worker_info,
    'password': password,
  }

  try:
    req = requests.post(remote + '/api/request_version', data=json.dumps(payload), headers={'Content-type': 'application/json'}, timeout=HTTP_TIMEOUT)
    req = json.loads(req.text)

    if 'version' not in req:
      print 'Incorrect username/password'
      time.sleep(5)
      sys.exit(1)

    if req['version'] > WORKER_VERSION:
      print 'Updating worker version to %d' % (req['version'])
      #update()

    req = requests.post(remote + '/api/request_task', data=json.dumps(payload), headers={'Content-type': 'application/json'}, timeout=HTTP_TIMEOUT)
    req = json.loads(req.text)
  except:
    sys.stderr.write('Exception accessing host:\n')
    traceback.print_exc()
    time.sleep(10)
    return

  if 'error' in req:
    raise Exception('Error from remote: %s' % (req['error']))

  # No tasks ready for us yet, just wait...
  if 'task_waiting' in req:
    print 'No tasks available at this time, waiting...'
    time.sleep(10)
    return

  success = True
  run, task_id = req['run'], req['task_id']
  try:
    run_games(worker_info, password, remote, run, task_id)
  except:
    sys.stderr.write('\nException running games:\n')
    traceback.print_exc()
    success = False
  finally:
    payload = {
      'username': worker_info['username'],
      'password': password,
      'run_id': str(run['_id']),
      'task_id': task_id
    }
    try:
      requests.post(remote + '/api/failed_task', data=json.dumps(payload), headers={'Content-type': 'application/json'}, timeout=HTTP_TIMEOUT)
    except:
      pass
    sys.stderr.write('Task exited\n')

  return success
Пример #19
0
def db_write(db_uri, measurement, value, timestamp):
    try:
        payload = "%s value=%s %d" % (measurement, value, timestamp)
        requests.post(db_uri, data=payload)
    except requests.exceptions.ConnectionError:
        sys.stderr.write("error: Connection to local influxdb failed\n")
        sys.exit(5)
Пример #20
0
def send_message(data=None):
    """function for sending sms.
        validates if user is valid > sends message > redirects to source path
        Assumes URL of the form /smsapi?number=12341234&message=message&source=/url
    """
    number = request.args.get('number')
    message = request.args.get('message')
    source = request.args.get('source', '/')
    anonymous = request.args.get('anonymous')

    if message is not None:
        if len(message) > 141:
            abort(400)
    
    if number is None:
        abort(400)

    if(anonymous==None):
        logMessage(number,message)

    if Production:
        requests.post(os.environ['BLOWERIO_URL'] + '/messages', data={'to': '+' + number, 'message': message})
    else:      
        app.logger.info(str({'to': '+' + number, 'message': message}))

         
        

    return  redirect("."+source)
Пример #21
0
def main():
    url = "http://localhost:4000/jsonrpc"
    headers = {'content-type': 'application/json'}

    # Example echo method
    payload = {
        "method": "echo",
        "params": ["echome!"],
        "jsonrpc": "2.0",
        "id": 0,
    }
    response = requests.post(
        url, data=json.dumps(payload), headers=headers).json()

    assert response["result"] == "echome!"
    assert response["jsonrpc"] == "2.0"
    assert response["id"] == 0

    # Example add method
    payload = {
        "method": "add",
        "params": [1, 2],
        "jsonrpc": "2.0",
        "id": 1,
    }
    response = requests.post(
        url, data=json.dumps(payload), headers=headers).json()

    assert response["result"] == 3
    assert response["jsonrpc"] == "2.0"
    assert response["id"] == 1

    # Example foobar method
    payload = {
        "method": "foobar",
        "params": {"foo": "json", "bar": "-rpc"},
        "jsonrpc": "2.0",
        "id": 3,
    }
    response = requests.post(
        url, data=json.dumps(payload), headers=headers).json()

    assert response["result"] == "json-rpc"
    assert response["jsonrpc"] == "2.0"
    assert response["id"] == 3

    # Example exception
    payload = {
        "method": "add",
        "params": [0],
        "jsonrpc": "2.0",
        "id": 4,
    }
    response = requests.post(
        url, data=json.dumps(payload), headers=headers).json()

    assert response["error"]["message"] == "Invalid params"
    assert response["error"]["code"] == -32602
    assert response["jsonrpc"] == "2.0"
    assert response["id"] == 4
Пример #22
0
    def send_data(self, eventdata, spooledevent=False):
        # only send if there is data to be sent
        success = None
        if eventdata:
            tries = 0
            r = None
            # If at first you don't succeed, try again. And again, and again, and again, and again.
            # Server must return 200 OK or we will assume the delivery failed.
#            while tries <= 5:
            try:
                headers = {'User-Agent': self.useragent,
                'Content-Type': 'application/json'}
                url = self.send_to
                if self.key:
                    r = requests.post(url, headers=headers, data=json.dumps(eventdata), 
                        verify=self.verify, cert=(self.cert, self.key))
                elif url.startswith('https'):
                    r = requests.post(url, headers=headers, data=json.dumps(eventdata), verify=self.verify)
                else:
                    r = requests.post(url, headers=headers, data=json.dumps(eventdata))
                success = r.status_code
                if not r.status_code == 200:
                    if not spooledevent:
                        spooler.spool_data(json.dumps(eventdata))
                        errorstr = "Warning: server unable to accept events. Spooling events to file."
                        print >> sys.stderr, errorstr
                else:
                    self.write_last_event(eventdata)
            except ConnectionError as e:
                if not spooledevent:
                    spooler.spool_data(json.dumps(eventdata))
                    errorstr = "Warning: could not reach {}.".format(self.send_to)
                    print >> sys.stderr, errorstr
        return success
Пример #23
0
    def test_diff(self):
        r = requests.post(self.url("/test_diff?edit"), data={
            "body": "# test diff\n\n"
        })
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)

        r = requests.post(self.url("/test_diff?edit"), data={
            "body": "# test diff\n\nadd an newline here \n"
        })
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)

        r = requests.get(self.url("/test_diff?history"))
        self.assertRegexpMatches(r.text, r'<a href="\?version=[0-9a-f]{40}">')

        version_re = re.compile(r'<a href="\?version=([0-9a-f]{40})">')
        versions = version_re.findall(r.text)

        self.assertEqual(len(versions), 2)

        r = requests.get(self.url("/test_diff?diff=%s,%s" % (versions[0], versions[1])))
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)
        self.assertIn(r'Diff for file from %s to %s' % (versions[0], versions[1]), r.text)

        r = requests.get(self.url("/test_diff?diff=%s,%s" % (versions[0][:13], versions[1][:13])))
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)
        self.assertIn(r'Diff for file from %s to %s' % (versions[0][:13], versions[1][:13]), r.text)

        r = requests.get(self.url("/test_diff?diff=%syyyy,xxxx%s" % (versions[0][:13], versions[1][:13])))
        self.assertGreaterEqual(r.status_code, 400)
        self.assertLess(r.status_code, 500)
Пример #24
0
 def send_mail(self, request):
     fn = self.cleaned_data['firstname']
     ln = self.cleaned_data['lastname']
     subj = self.cleaned_data['subject']
     fr = self.cleaned_data['email']
     msg = self.cleaned_data['message']
     try:
         requests.post(
             "https://api.mailgun.net/v2/neumerance.mailgun.org/messages",
             auth= ("api", "key-85jxyi84br32xu0cizfihmmbbxv576j5"),
             data={
                   "from":fr,
                   "to": ["*****@*****.**",],
                   "subject": subj,
                   "text": msg
             }
          )
         messages.info(request, 
                       "Thank you for sending me your feedback, I will get back to you as soon as possible.",
                       extra_tags="success"
                       )
     except:
         messages.info(request, 
                       "Unable to send your message at this time, Please try again later.",
                       extra_tags="error"
                       )
Пример #25
0
    def test_save_option(self):
        data = {"Title": "title", "Toc": "false", "HeadingNumber": "i.a.a.i"}
        # dir does not exists
        r = requests.post(self.url("test") + "/test_dir_not_exists?option", data=json.dumps(data))
        self.assertEqual(r.status_code, 400)
        self.assertEqual(json.loads(r.content), {"code": 1})

        # missing Title field
        r = requests.post(self.url("test.md") + "?option", data=json.dumps({"Toc": "false", "HeadingNumber": "i.a.a.i"}))
        self.assertEqual(r.status_code, 400)
        self.assertEqual(json.loads(r.content), {"code": 1})

        # Toc show be either `true` or `false`
        r = requests.post(self.url("test.md") + "?option", data=json.dumps({"Title": "test", "Toc": "falsexxx", "HeadingNumber": "i.a.a.i"}))
        self.assertEqual(r.status_code, 400)
        self.assertEqual(json.loads(r.content), {"code": 1})

        # HeadingNumber format shoule be `i.a.a.i`
        r = requests.post(self.url("test.md") + "?option", data=json.dumps({"Title": "test", "Toc": "false", "HeadingNumber": "i.a.a.iiii"}))
        self.assertEqual(r.status_code, 400)
        self.assertEqual(json.loads(r.content), {"code": 1})

        # succeeded
        r = requests.post(self.url("test1xxx") + "?option", data=json.dumps({"Title": "test", "Toc": "false", "HeadingNumber": "i.a.a.i"}))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.headers["Content-Type"], "application/json")
        self.assertEqual(json.loads(r.content), {"code": 0})
        self.assertEqual(json.loads(open(self.cwd + "/test1xxx.md.option.json", "r").read()), {"Title": "test", "Toc": "false", "HeadingNumber": "i.a.a.i", "Theme": "", "Host": ""})
Пример #26
0
def verify_signature(engine, signature, remote, payload, concurrency):
  if concurrency > 1:
    busy_process = subprocess.Popen([engine], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    busy_process.stdin.write('setoption name Threads value %d\n' % (concurrency-1))
    busy_process.stdin.write('go infinite\n')

  try:
    bench_sig = ''
    print 'Verifying signature of %s ...' % (os.path.basename(engine))
    with open(os.devnull, 'wb') as f:
      p = subprocess.Popen([engine, 'bench'], stderr=subprocess.PIPE, stdout=f, universal_newlines=True)
    for line in iter(p.stderr.readline,''):
      if 'Nodes searched' in line:
        bench_sig = line.split(': ')[1].strip()
      if 'Nodes/second' in line:
        bench_nps = float(line.split(': ')[1].strip())

    p.wait()
    if p.returncode != 0:
      raise Exception('Bench exited with non-zero code %d' % (p.returncode))

    if int(bench_sig) != int(signature):
      requests.post(remote + '/api/stop_run', data=json.dumps(payload))
      raise Exception('Wrong bench in %s Expected: %s Got: %s' % (engine, signature, bench_sig))

  finally:
    if concurrency > 1:
      busy_process.stdin.write('quit\n')
      busy_process.kill()

  return bench_nps
Пример #27
0
def analyze(result_directory=None, upload=False, compute_cheapest=0, compute_average_per_day=False, compute_average_per_trip_length=False, compute_average_per_days_in_advance=False):
    data, meta_data = read_results(result_directory)

    result = []

    result.append("Leaving from %s going to %s" % (meta_data['from'], meta_data['to']))
    result.append("Size of date range: %s (days)" % meta_data['window_size'])
    result.append("Minimum trip length: %s (days)" % meta_data['min_trip'])
    result.append("Maximum trip length: %s (days)" % meta_data['max_trip'])

    if compute_cheapest:
        result.extend(get_cheapest(data, compute_cheapest))

    if compute_average_per_day:
        result.extend(get_average_per_day(data))

    if compute_average_per_trip_length:
        result.extend(get_average_per_trip_length(data))

    if compute_average_per_days_in_advance:
        result.extend(get_average_per_days_in_advance(data))

    if upload:
        upload_url = settings.DEBUG_UPLOAD_URL if settings.DEBUG else settings.UPLOAD_URL
        requests.post(upload_url, data={'content': json.dumps(result)})

    print "\n".join(result)
Пример #28
0
    def test_file_dir_with_same_name(self):
        text = u"file a content"
        r = requests.post(self.url("a?edit"), data={
            "body": text
        })
        self.assertIn(text, r.text)
        self.assertIn("strapdown.min.js", r.text)

        text2 = "does not matter"
        r = requests.post(self.url("a/b?edit"), data={
            "body": text2
        })
        self.assertIn(text2, r.text)
        self.assertIn("strapdown.min.js", r.text)

        # should be the file
        r = requests.get(self.url("a"))
        self.assertIn(text, r.text)
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)

        # should be the directory
        r = requests.get(self.url("a/"))
        self.assertNotIn(text, r.text)
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)
        self.assertIn('Directory Listing', r.text)
        self.assertIn('b.md', r.text)

        # should be file b
        r = requests.get(self.url("a/b"))
        self.assertIn(text2, r.text)
        self.assertGreaterEqual(r.status_code, 200)
        self.assertLess(r.status_code, 300)
Пример #29
0
    def setUp(self):
        """
        # Create a db
        """
        headers = {'Content-Type': 'application/json; charset=utf-8'}
        db_data = {'name': 'testDB'}
        response = requests.post(__db_url__, json=db_data, headers=headers)
        if response.status_code == 201:
            self.assertEqual(response.status_code, 201)
        else:
            self.assertEqual(response.status_code, 404)
        # Create a server
        response = requests.get(__db_url__)
        value = response.json()
        if value:
            db_length = len(value['databases'])
            last_db_id = value['databases'][db_length-1]['id']

            url = 'http://%s:8000/api/1.0/databases/%u/servers/' % \
                (__host_or_ip__,last_db_id)

            data = {'description': 'test', 'hostname': __host_or_ip__, 'name': 'test'}
            response = requests.post(url, json=data, headers=headers)
            if response.status_code == 201:
                self.assertEqual(response.status_code, 201)
            else:
                self.assertEqual(response.status_code, 404)
        else:
            print "The database list is empty"
Пример #30
0
def postfile(host, port, user, auth_token, db, table, filename, lines, version):
    """
        post data reading from file to server
    """
    if not os.path.isfile(filename):
        click.echo('[ERROR] Filename not exist')
        return

    headers = {'X-USERNAME':user, 'X-AUTH-TOKEN':auth_token}
    url = "http://%s:%s/%s/%s/%s" % (host, port, version, db, table)

    total_lines = wc['-l', filename]().split()[0]
    over_lines = 0
    post_data = []
    for data in open(filename):
        js = json.loads(data)
        js['tags']= js['tags'][0] if len(js['tags']) else ''
        post_data.append(js)
        if len(post_data) == lines:
            over_lines = over_lines + lines
            r = requests.post(url, data=json.dumps(post_data), headers=headers)
            if r.status_code != 200:
                click.echo("Invalid response from server")
                return
            click.echo('Post %s/%s lines data to ingestion Server' % (over_lines, total_lines))
            post_data = []

    if len(post_data) > 0:
        over_lines = over_lines + len(post_data)
        requests.post(url, data=json.dumps(post_data), headers=headers)
        click.echo('Post %s/%s lines data to ingestion Server' % (over_lines,total_lines))

    click.echo("All data post to ingestion server")
Пример #31
0
def yandex_speech(input_link: str, bucket: str, aws_secret_access_key: str,
                  aws_access_key_id: str, API_key: str) -> str:
    """
    :param input_link: path to the wav-file
    :param bucket: name of bucket at Yandex.Cloud
    :param aws_secret_access_key: secret code of the access key
    :param aws_access_key_id: ID of the access key
    :param API_key: ID of the API_key
    :return:
    """
    # загрузка в облако
    session = boto3.session.Session(region_name="ru-central1", aws_secret_access_key=aws_secret_access_key,
                                    aws_access_key_id=aws_access_key_id)
    s3 = session.client(service_name='s3', endpoint_url='https://storage.yandexcloud.net/')
    s3.upload_file(input_link, bucket, 'obj.wav')

    file_link = 'https://storage.yandexcloud.net/' + bucket + '/obj.wav'
    POST = "https://transcribe.api.cloud.yandex.net/speech/stt/v2/longRunningRecognize"

    body = {
        "config": {
            "specification": {
                "languageCode": "ru-RU",
                "model": "general:rc",
                "audioEncoding": "LINEAR16_PCM",
                "sampleRateHertz": 8000,
                "audioChannelCount": 1
            }
        },
        "audio": {
            "uri": file_link
        }
    }

    header = {'Authorization': 'Api-Key {}'.format(API_key)}

    # Отправить запрос на распознавание.
    req = requests.post(POST, headers=header, json=body)
    data = req.json()
    id_ = data['id']

    GET = "https://operation.api.cloud.yandex.net/operations/" + str(id_)

    # Запрашивать на сервере статус операции, пока распознавание не будет завершено.
    wait = 0
    while wait <= 60:

        time.sleep(1)
        wait += 1

        req = requests.get(GET, headers=header).json()

        if req['done']:
            break

    # удаление объекта в облаке
    for_deletion = [{'Key': 'obj.wav'}]
    s3.delete_objects(Bucket=bucket, Delete={'Objects': for_deletion})

    # Текст результатов распознавания.
    output_text = ''

    if req['done']:
        for chunk in req['response']['chunks']:
            c = chunk['alternatives'][0]['text']
            output_text += ' ' + c
    else:
        raise TimeoutError('no response from YSK')

    return output_text
Пример #32
0
 def post(self, location='/%s/1' % default_index, **kwargs):
     return requests.post(self.url + location, headers=http_api_headers, auth=self.auth, **kwargs)
Пример #33
0
 def create_project(self, name, description):
     url = "%s%s" % (self.endpoint, "/projects.json")
     data = {"project": {"name": name, "description": description}}
     data = json.dumps(data)
     r = post(url, data=data, headers=self.headers, verify=False)
     return r
Пример #34
0
def send_mess(chat, text):
    params = {'chat_id': chat, 'text': text}
    response = requests.post(url + 'sendMessage', data=params)
    return response
Пример #35
0
def sync(multi, identity):
    """
    Upload records to each registered server.

    Each user, bid, offer, etc. (i.e. anything except actual payments) is 
    stored as document across a public database that is maintained across
    a network of paid servers. This command pushes the documents you have
    created to the servers from which you have purchased hosting. 
    """
    (log, user, key, urls) = init(multi, identity)

    click.echo("User: "******"No buckets registered. Run 'rein request' to continue.")
        return

    create_placements(rein.engine)

    upload = []
    nonce = {}
    for url in urls:
        nonce[url] = get_new_nonce(rein, url)
        if nonce[url] is None:
            continue
        check = get_user_documents(rein) 
        if len(check) == 0:
            click.echo("Nothing to do.")

        for doc in check:
            if len(doc.contents) > 8192:
                click.echo('Document is too big. 8192 bytes should be enough for anyone.')
                log.error("Document oversized %s" % doc.doc_hash)
            else:
                placements = get_placements(rein, url, doc.id)
                           
                if len(placements) == 0:
                    upload.append([doc, url])
                else:
                    for plc in placements:
                        if get_remote_document_hash(rein, plc) != doc.doc_hash:
                            upload.append([doc, url])
    
    failed = []
    succeeded = 0
    for doc, url in upload:
        placements = get_placements(rein, url, doc.id)
        if len(placements) == 0:
            remote_key = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits)
                                 for _ in range(32))
            plc = Placement(doc.id, url, remote_key, False, rein.testnet)
            rein.session.add(plc)
            rein.session.commit()
        else:
            plc = placements[0]
            for p in placements[1:]:
                rein.session.delete(p)
                rein.session.commit()

        if len(doc.contents) > 8192:
            log.error("Document oversized %s" % doc.doc_hash)
            click.echo('Document is too big. 8192 bytes should be enough for anyone.')
        elif nonce[url] is None:
            continue
        else:
            message = plc.remote_key + doc.contents + user.daddr + nonce[url]
            message = message.decode('utf8')
            message = message.encode('ascii')
            signature = sign(user.dkey, message)
            data = {"key": plc.remote_key,
                    "value": doc.contents,
                    "nonce": nonce[url],
                    "signature": signature,
                    "signature_address": user.daddr,
                    "owner": user.maddr,
                    "testnet": rein.testnet}
            body = json.dumps(data)
            headers = {'Content-Type': 'application/json'}
            answer = requests.post(url='{0}put'.format(url), headers=headers, data=body)
            res = answer.json()
            if 'result' not in res or res['result'] != 'success':
                log.error('upload failed doc=%s plc=%s url=%s' % (doc.id, plc.id, url))
                failed.append(doc)
            else:
                plc.verified += 1
                rein.session.commit()
                log.info('upload succeeded doc=%s plc=%s url=%s' % (doc.id, plc.id, url))
                click.echo('uploaded %s' % doc.doc_hash)
                succeeded += 1

    for url in urls:
        if nonce[url] is None:
            continue
        sel_url = url + 'nonce?address={0}&clear={1}'
        answer = requests.get(url=sel_url.format(user.maddr, nonce[url]))
        log.info('nonce cleared for %s' % (url))

    click.echo('%s docs checked on %s servers, %s uploads done.' % (len(check), len(urls), str(succeeded)))
Пример #36
0
def APiCaller(parameters={}):
    response = requests.post(API_url, json=parameters)
    #[{"eventTime": "2017-04-09T18:42:11Z", "userIdentity_userName": "******"}, {"eventTime": "2017-04-09T22:27:58Z", "userIdentity_userName": "******"}
    return ast.literal_eval(response.json())
Пример #37
0
def send_ptm_data_to_ems (target_Data) :
    response_json = {}
    with open("config.json") as f:
        tmp_config_json = json.loads(f.read())
    target = tmp_config_json[target_Data]
    ems_url = tmp_config_json["EMS Server URL"] + target['url']
    # print(ems_url)
    if target_Data == "device":
        try:
            target['rq_param_send_time'] = datetime.fromtimestamp(int(str(time.time())[0:10])).strftime('%Y%m%d%H%M%S')
            res = requests.post(ems_url, headers=headers, data=json.dumps(target))
            # print('\n status_code : ' + str(res.status_code))
            response_json = res.json()
            # prnt(response_json)
            # device에 대한 정보 받아와서 보여주
            return response_json #response_json
        except:
            print("Device 기록에 실패했습니다.")
    elif target_Data == "regist" :
        try:
            target['rq_param_parameter'] = eid
            res = requests.post(ems_url, headers=headers, data=json.dumps(target))
            # print('\n status_code : ' + str(res.status_code))
            response_json = res.json()
            # prnt(response_json)
            # device에 대한 정보 받아와서 보여주
            return response_json#response_json
        except:
            print("Device 등록에 실패했습니다.")

    elif target_Data == "params" :
        try:
            res = requests.post(ems_url, headers=headers, data=json.dumps(target))
            # print('\n status_code : ' + str(res.status_code))
            response_json = res.json()
            prnt(response_json)
            # prnt(response_json)
            # device에 대한 정보 받아와서 보여주
            return response_json
            # res = requests.post(ems_url, headers=headers, data=json.dumps(target))
            #print('\n status_code : ' + str(res.status_code))
            #prnt(res.json())
            #response_json = res.json()
            # stateOfcharge = stateParams['rs_stateParameter'][0]['stateOfcharge'] 응답 받고 수신값
            # genRatio = stateParams['rs_stateParameter'][0]['genRatio']
            # lossRatio = stateParams['rs_stateParameter'][0]['lossRatio']
            # print('\n SoC : ' + str(stateOfcharge))
            # print('\n genRatio : ' + str(genRatio))
            # print('\n lossRatio : ' + str(lossRatio))
            #return print(target)#response_json
        except:
            print("EMS Data loading에 실패했습니다.")

    elif target_Data == "contractMsg" :
        try:
            target['rq_param_parameter']['dep2_rq_param_id'] = deal_info_completed["deal_id"]
            target['rq_param_parameter']['dep2_rq_param_seller'] = deal_info_completed["seller_eid"]
            target['rq_param_parameter']['dep2_rq_param_buyer'] = deal_info_completed["buyer_eid"]
            target['rq_param_parameter']['dep2_rq_param_price'] = deal_info_completed["price"]
            target['rq_param_parameter']['dep2_rq_param_quantity'] = deal_info_completed["kwh"]
            target['rq_param_parameter']['dep2_rq_param_tr_st_time'] = datetime.fromtimestamp(int(deal_info_completed["txTimestamp"][0:10]) + tmp_config_json["start_delay"]).strftime('%Y%m%d%H%M%S')
            #complete 되고 tmp_config_json["start_delay"] = 300초 만큼 딜레이 후 전력 거래 시#
            target['rq_param_parameter']['dep2_rq_param_tr_ed_time'] = ""
            target['rq_param_time'] = datetime.fromtimestamp(int(str(time.time())[0:10])).strftime('%Y%m%d%H%M%S')

            res = requests.post(ems_url, headers=headers, data=json.dumps(target))
            # print('\n status_code : ' + str(res.status_code))
            response_json = res.json()
            # prnt(response_json)
            # device에 대한 정보 받아와서 보여주
            return response_json
            #res = requests.post(ems_url, headers=headers, data=json.dumps(target))
            #print('\n status_code : ' + str(res.status_code))
            #prnt(res.json())
            #response_json = res.json()
            # return print(target)#response_json
        except:
            print("Contract Msg 전송에 실패했습니다.")
Пример #38
0
 def _make_post(self, endpoint, body):
     url = self.base_endpoint + endpoint
     return requests.post(url, json=body,
                          headers=self._get_headers()).json()
landmark_analyze_url = vision_base_url + "models/landmarks/analyze"

# Set image_url to the URL of an image that you want to analyze.
#image_url = "https://upload.wikimedia.org/wikipedia/commons/f/f6/" + \
#   "Bunker_Hill_Monument_2005.jpg"

#image_url = "https://upload.wikimedia.org/wikipedia/ja/thumb/3/3e/MtFuji_FujiCity.jpg/320px-MtFuji_FujiCity.jpg"
#image_url = "https://i.ytimg.com/vi/Fs1W5WrGTjE/hqdefault.jpg"
image_url = "https://clicktraveltips.com/wp-content/uploads/2013/04/Golden-Gate-Bridge.jpg"
image_url = "https://cdntct.com/tct/pic/china-tour-pic/beijing/tiananmen-04.jpg"
#image_url = "https://cache-graphicslib.viator.com/graphicslib/thumbs360x240/7845/SITours/%E3%82%A8%E3%83%83%E3%83%95%E3%82%A7%E3%83%AB%E5%A1%94%E3%81%B8%E3%81%AE%E5%84%AA%E5%85%88%E5%85%A5%E5%A0%B4%E3%83%81%E3%82%B1%E3%83%83%E3%83%88%EF%BC%88%E3%83%9B%E3%82%B9%E3%83%88%E4%BB%98%E3%81%8D%EF%BC%89-in-paris-299567.jpg"
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
params = {'model': 'landmarks'}
data = {'url': image_url}
response = requests.post(landmark_analyze_url,
                         headers=headers,
                         params=params,
                         json=data)
response.raise_for_status()

# The 'analysis' object contains various fields that describe the image. The
# most relevant landmark for the image is obtained from the 'result' property.
analysis = response.json()
assert analysis["result"]["landmarks"] is not []
print(json.dumps(analysis, indent=4))
landmark_name = ''
if (analysis["result"]["landmarks"]):
    landmark_name = analysis["result"]["landmarks"][0]["name"].capitalize()

# Display the image and overlay it with the landmark name.
image = Image.open(BytesIO(requests.get(image_url).content))
Пример #40
0
import numpy as np
from collections import OrderedDict
import time
import traceback
import logging
import pdb


rtData={
    "client_id":"curl",
    "username":os.environ["KEYCLOAK_USER"],
    "password":os.environ["KEYCLOAK_PWD"],
    "grant_type":"password",
    "scope":"openid offline_access"
}
refreshData=requests.post("https://login.akvo.org/auth/realms/akvo/protocol/openid-connect/token",rtData).json();

def getAccessToken():
    acData={
    "client_id":"curl",
    "refresh_token":refreshData["refresh_token"],
    "grant_type":"refresh_token"
    }
    accessData = requests.post("https://login.akvo.org/auth/realms/akvo/protocol/openid-connect/token",acData).json()
    return accessData["access_token"]


def getResponse(url):
    # print(url)
    header={
        "Authorization":"Bearer "+ getAccessToken() ,
Пример #41
0
 def test7_vote(self) :
     tester = app.test_client(self)
     response = requests.post("http://0.0.0.0:8080/poll/cast/vote",data = json.dumps({"Account":"0xdc2875d889Bbb48bF7097dC12191E88C1C8Cfc23","CandidateId":0}))
     self.assertEqual(response.status_code,200)
Пример #42
0
check_id = resp.content
print(check_id)
#string_input = resp.json()
string_input = resp.json()
final_str = (string_input['test_input']['text'])

string_input = final_str
count = 0
for i in string_input:
    if i =='.':
        count +=1
data1 = {
    "test_session": 13,
    "output": { "sentenceCount": count  }, 
    "challenge": 3  
}

data2 = json.dumps(data1)

#print(data2)

headers = {'Content-type':'application/json', 'Accept':'application/json'}

url = "https://code-riddler.herokuapp.com/api/v1/testsessionchallenges/output/"

check = requests.post(url,data = data2 ,auth = (username,password),headers =headers)
#print(check.status_code)
print(check.content)

Пример #43
0
from hashlib import sha1
import email.utils
import hmac
import requests

secret = "xxxx-xxxx-xxx-xxx-xxxx"  # replace with secret from email
username = "******"  # replace with username from email
url = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'  # replace with url from email

dt = email.utils.formatdate(usegmt="true")
stringToSign = 'date: ' + dt

encodedSignature = hmac.new(secret, stringToSign,
                            sha1).digest().encode("base64").rstrip('\n')

hmacAuth = 'hmac username="******",algorithm="hmac-sha1",headers="date",signature="' + encodedSignature + '"'

headers = {'date': dt, 'Authorization': hmacAuth}

data = {"companyId": 386}

endpoint = url + "marketplace/v1/pricing/global"
r = requests.post(endpoint, json=data, headers=headers)
print(r.text)
Пример #44
0
 def test1_addCandididates(self) :
     tester = app.test_client(self)
     response = requests.post("http://0.0.0.0:8080/poll/add/candidate",data = json.dumps({"Account":"0xdc2875d889Bbb48bF7097dC12191E88C1C8Cfc23","CandidateName":"Kevin Kingsly"}))
     self.assertEqual(response.status_code,200)
Пример #45
0
def test_post_formdata(pub_data):
    data = {'userName':'******'}
    h = {'token':pub_data['token']}
    r = requests.post('http://qa.yansl.com:8084/user/lock',data=data,headers=h)
    print(r.text)
Пример #46
0
 def test6_getinfo(self) :
     tester = app.test_client(self)
     response = requests.post("http://0.0.0.0:8080/poll/get/information",data = json.dumps({"Account":"0xdc2875d889Bbb48bF7097dC12191E88C1C8Cfc23"}))
     self.assertEqual(response.status_code,200)
     print("data : ",response.json(),flush=True)
# 텍스트 템플릿 형식 만들기
template = {
    "object_type": "text",
    "text": text,
    "link": {
        "web_url": weather_url,
        "mobile_web_url": weather_url
    },
    "button_title": "날씨 상세보기"
}

# JSON 형식 -> 문자열 변환
payload = {"template_object": json.dumps(template)}

# 카카오톡 보내기
res = requests.post(kakaotalk_template_url, data=payload, headers=kheaders)

if res.json().get('result_code') == 0:
    print('메시지를 성공적으로 보냈습니다.')
else:
    print('메시지를 성공적으로 보내지 못했습니다. 오류메시지 : ' + str(res.json()))

# 리스트 템플릿 형식 만들기
contents = []
template = {
    "object_type":
    "list",
    "header_title":
    "현재 날씨에 따른 옷 추천",
    "header_link": {
        "web_url": weather_url,
Пример #48
0
def test_post_upload_file(pub_data):
    data = {'file':open('aa.xls','rb')}
    h = {'token':pub_data['token']}
    r = requests.post('http://qa.yansl.com:8084/product/uploaprodRepertory',files=data,headers=h)
    print(r.text)
                                                                                 auth=base64_string,
                                                                                 origin=config['api_base_url'])
        for header, value in headers.iteritems():
            if header and value:
                request_headers += '\r\n{header}: {value}'.format(
                    header=header, value=value)

        # make request
        response = None
        verify = False
        timeout = 60
        if method == 'GET':
            response = requests.get(
                url, auth=auth, headers=headers, verify=verify, timeout=timeout)
        elif method == 'POST':
            response = requests.post(
                url, auth=auth, headers=headers, data=payload, verify=verify, timeout=timeout)
        elif method == 'PUT':
            response = requests.put(
                url, auth=auth, headers=headers, data=payload, verify=verify, timeout=timeout)
        elif method == 'DELETE':
            response = requests.delete(
                url, auth=auth, headers=headers, verify=verify, timeout=timeout)
        else:
            response = requests.options(
                url, auth=auth, headers=headers, verify=verify, timeout=timeout)

        headers = collections.OrderedDict(sorted(response.headers.items()))
        code_description = requests.status_codes._codes[response.status_code][0]
        code_description = code_description.replace('_', ' ').title()
        http_version = str(response.raw.version)
        if len(http_version) > 1:
Пример #50
0
def test_post_json():
    data = {'pwd':'abc123','userName':'******'}
    r = requests.post('http://qa.yansl.com:8084/login',json=data)
    print(r.text)
Пример #51
0
def update_parcel_department_effectivefirefighting_rollup(fd_id):
    """
    Update for one department for the effective fire fighting force
    """
    stationlist = FireStation.objects.filter(department_id=fd_id)
    dept = FireDepartment.objects.filter(id=fd_id)
    staffingtotal = "1"  # assume staffing minimum of 1 for now

    if dept[0].geom is None:

        print "No geometry for the department " + dept[0].name

    else:
        print "Calculating Response times and staffing for:  " + dept[0].name + ' at ' + time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())

        try:
            #  Use Headquarters geometry if there is no Statffing assets
            if len(stationlist) < 1:
                drivetimeurl = 'http://gis.iaff.org/arcgis/rest/services/Production/PeopleCountOct2012/GPServer/PeopleCountOct2012/execute?f=json&Facilities={"features":[{"geometry":{"x":' + str(dept[0].headquarters_geom.x) + ',"spatialReference":{"wkid":4326},"y":' + str(dept[0].headquarters_geom.y) + '}}],"geometryType":"esriGeometryPoint"}&env:outSR=4326&text_input=' + staffingtotal + '&returnZ=false&returnM=false'
                getdrivetime = requests.get(drivetimeurl)

            else:
                drivetimegeom = []
                staffingtotal = ""
                for fireStation in stationlist:
                    # staffing
                    assetlist = Staffing.objects.filter(firestation_id=fireStation.id)
                    stationstafftotal = 0
                    for staff in assetlist:
                        stationstafftotal = stationstafftotal + staff.personnel

                    # geometry
                    stationasset = {}
                    stationasset["spatialReference"] = {"wkid": 4326}
                    stationasset["y"] = round(fireStation.geom.y, 5)
                    stationasset["x"] = round(fireStation.geom.x, 5)
                    stationgeom = {}
                    stationgeom["geometry"] = stationasset
                    drivetimegeom.append(stationgeom)
                    staffingtotal = staffingtotal + str(stationstafftotal) + ','

                drivepostdata = {}
                drivepostdata['f'] = 'pjson'
                drivepostdata['returnZ'] = False
                drivepostdata['returnM'] = False
                drivepostdata['env:outSR'] = 4326
                drivepostdata['text_input'] = staffingtotal[:-1]
                drivepostfeatures = {}
                drivepostfeatures['features'] = drivetimegeom
                drivepostfeatures['geometryType'] = "esriGeometryPoint"
                drivepostdata['Facilities'] = json.dumps(drivepostfeatures)

                # need to run async so it doesn't time out
                # getdrivetime = requests.post("http://gis.iaff.org/arcgis/rest/services/Production/PeopleCountOct2012/GPServer/PeopleCountOct2012/execute", data=drivepostdata)
                getdrivetime = requests.post("http://gis.iaff.org/arcgis/rest/services/Production/PeopleCount2017_V2/GPServer/PeopleCount2017/submitJob", data=drivepostdata)

            get_async_efff_service_status(json.loads(getdrivetime.content)['jobId'], dept[0])

        except KeyError:
            print 'Drive Time Failed for ' + dept[0].name

        except IntegrityError:
            print 'Drive Time Failed for ' + dept[0].name

        except:
            print 'Drive Time Failed for ' + dept[0].name
Пример #52
0
    def request_action(self, phone, header, cookie):

        # 解析cookie里面snsInfo数据
        try:
            cookie_dic = json.loads(cookie.split(';')[3].split('=')[1])
        except:
            return
        sleep_time = 0
        blind_url = 'https://h5.ele.me/restapi/v1/weixin/' + cookie_dic[
            'openid'] + '/phone'
        lucky_url = 'https://h5.ele.me/restapi/marketing/promotion/weixin/' + cookie_dic[
            'openid']
        blind_data = {
            'sign': cookie_dic['eleme_key'],
            'method': 'phone',
            'phone': str(phone),
        }

        avater = cookie_dic['avatar']
        user_name = phone[:3] + '*' * 4 + phone[7:9]
        sleep(0.1)

        request_data = {
            'device_id': self.query['device_id'],
            'group_sn': self.query['sn'],
            'hardware_id': self.query['hardware_id'],
            'method': 'phone',
            'phone': str(phone),
            'platform': self.query['platform'],
            'refer_user_id': self.query['refer_user_id'],
            'sign': cookie_dic['eleme_key'],
            'track_id': self.query['track_id'],
            'unionid': 'f**k',
            'theme_id': self.query['theme_id'],
            'weixin_avatar': avater,
            'weixin_username': user_name,
        }

        # 两个不同请求分开放
        try:
            get_post_result = requests.post(lucky_url,
                                            data=json.dumps(request_data),
                                            headers=header).text
            sleep(sleep_time)
        except:
            get_post_result = False
            self.output_json({
                "errorCode": "10002",
                "msg": "Parameter error",
                "other": "post"
            })

        try:
            # sleep(3)
            get_put_result = requests.put(blind_url,
                                          data=json.dumps(blind_data),
                                          headers=header).text
            soup_1 = BeautifulSoup(get_put_result, 'lxml')
            soup = BeautifulSoup(get_post_result, 'lxml').p.get_text()
            soup_string = json.loads(str(soup))

            try_times = last_times = big_number = 0
            promotion_records = soup_string['promotion_records']

            for i in range(len(promotion_records)):
                if promotion_records[i]['is_lucky'] or int(
                        promotion_records[i]['amount']) >= 4:
                    last_times += 1
                    big_number = float(promotion_records[i]['amount'])
                else:
                    try_times += 1

            return {
                'small_package': try_times,
                'big_package': last_times,
                'big_number': big_number
            }
        except:
            self.output_json({"errorCode": "10006", "msg": "Bad request"})
            self.error += 1
            self.begin(1)
Пример #53
0
import requests

cred = {
    'email':'*****@*****.**',
    'password':'******'
}

login = '******'
api = 'http://192.168.100.105:5000/users'

res = requests.post(login,json=cred)
token = res.json().get('token')
print(token)
if token:
    headers = {'Authorization':f'Bearer{token}'}
    print(headers)
    res = requests.get(api,headers=headers)
    print("bien")
else:
    print ("mal")
Пример #54
0
#!/usr/bin/python3
import requests
import json


print('\n 1. Login in Odoo and get access tokens:')
r = requests.post(
    'http://localhost:8069/api/auth/get_tokens',
    headers={'Content-Type': 'text/html; charset=utf-8'},
    data=json.dumps({
        'username': '******',
        'password': '******',
    }),
    # verify = False      # for TLS/SSL connection
)
print(r.text)
access_token = r.json()['access_token']


print('\n 2. res.partner - Read all (with filters in URL):')
r = requests.get(
    "http://localhost:8069/api/res.partner?filters=[('name','like','ompany'),('id','!=',50)]",
    headers={
        'Content-Type': 'text/html; charset=utf-8',
        'Access-Token': access_token
    },
    # verify = False      # for TLS/SSL connection
)
print(r.text)
Пример #55
0
def relay_call(name, data):
    return requests.post("http://{}/{}".format(relay_address, name),
                        headers={"content-type" : "application/json"},
                        data=json.dumps(data))
Пример #56
0
#!/usr/bin/python
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import requests as r
import json
r.packages.urllib3.disable_warnings(InsecureRequestWarning)

username = "******"
port = '8081'
base_url = 'https://' + username + '.code.engineering.nyu.edu:' + port + '/'

login_payload = {"username" : "john", "password" : "1234"}

r1 = r.post(base_url + 'user/login', verify=False, json=login_payload)
print "Response from login: "******"Session_id cookie: " + r1.cookies["session_id"]
	r2 = r.post(base_url + 'user/logout', verify=False, cookies=r1.cookies)
	print "Response from logout: " + r2.content
Пример #57
0
# Получение всех работ
print(requests.get('http://127.0.0.1:8080/api/jobs').json())
# Корректное получение одной работы
print(requests.get('http://127.0.0.1:8080/api/jobs/1').json())
# Ошибочный запрос на получение одной работы — неверный id
print(requests.get('http://127.0.0.1:8080/api/jobs/999').json())
# Ошибочный запрос на получение одной работы — строка
print(requests.get('http://127.0.0.1:8080/api/jobs/test').json())
# Верный запрос
print(
    requests.post('http://127.0.0.1:8080/api/jobs',
                  json={
                      'id': 99,
                      'job': '1',
                      'team_leader': 1,
                      'work_size': 1,
                      'collaborators': '1',
                      'is_finished': False
                  }).json())
# Не передан параметр is_finished
print(
    requests.post('http://127.0.0.1:8080/api/jobs',
                  json={
                      'id': 7,
                      'job': '1',
                      'team_leader': 1,
                      'work_size': 1,
                      'collaborators': '1'
                  }).json())
# Работа с существующим id
Пример #58
0
def severity(num_cars):
    max_cars = 96
    max_weight = 96*6000 # 96 * 3 tons  with 30% buffer
    print("max weight: " + str(max_weight))
    avg_car_weight = 4500 # 2 tons is avg weight of cars
    # severity values (ratio from weight of cars)
    # TODO: modify this to use max cars value
    sev_1 = 0 # 0
    sev_2 = int(max_weight/5) 
    sev_3 = sev_2 + int(max_weight/5) 
    sev_4 = sev_3 + int(max_weight/5) 
    sev_5 = sev_4 + int(max_weight/5)
    print("sev_1: %s sev_2: %s sev_3: %s sev_4: %s sev_5: %s max_weight: %s" % (sev_1, sev_2, sev_3, sev_4, sev_5, max_weight))

    # key: # of cars, value: the severity value
    # severities = {sev_1: 1, sev_2: 2, sev_3: 3, sev_4: 4, sev_5: 5}

    # extent - constant depending on bridge age
    # TODO: need to figure out a way to quantify age as a key for determining what age is
    # A, B, C, D, or E
    age = 2
    extent = {0: "A", 1: "B", 2: "C", 3: "D", 4: "E"}

    # first key value for tuple for querying in ECS table
    # constant for one bridge
    bridge_extent = extent[age]

    # STEP 1: retrieve ECS VALUE
    # TODO: modify the severity values based on the weight of cars passing through each point
    cars_at_points = num_cars
    weight_of_cars = cars_at_points*avg_car_weight
    print("weight of cars: " + str(weight_of_cars))
    severity_val = 1
    if weight_of_cars >= sev_1 and weight_of_cars < sev_2:
        severity_val = 1
    elif weight_of_cars >= sev_2 and weight_of_cars < sev_3:
        severity_val = 2
    elif weight_of_cars >= sev_3 and weight_of_cars < sev_4:
        severity_val = 3
    elif weight_of_cars >= sev_4 and weight_of_cars < sev_5:
        severity_val = 4
    # elif weight_of_cars >= sev_5:
    #     severity_val = 5
    elif (weight_of_cars >= sev_5 and weight_of_cars < max_weight) or weight_of_cars > max_weight:
        severity_val = 5
    

    print("severity_val: " + str(severity_val))

    A_severity = severity_val
    B_severity = severity_val
    C_severity = severity_val
    print("severities: " + str(A_severity))

    A_ECS = ECS_table[(bridge_extent, A_severity)] # (C, 2) = 2.1
    B_ECS = ECS_table[(bridge_extent, B_severity)] # (C, 3) = 3.2
    C_ECS = ECS_table[(bridge_extent, C_severity)] # (C, 4) = 4.1

    # print()
    # print("STEP 1")
    # print("A_ECS: " + str(A_ECS))
    # print("B_ECS: " + str(B_ECS))
    # print("C_ECS: " + str(C_ECS))
    # print()

    # STEP 2: retrieve EIF VALUE
    # B - most important (very high)
    # A, C - least important (low)
    # very high = 2, high = 1.5, medium = 1.2, low = 1.0
    A_EIF = 1.0
    B_EIF = 2.0
    C_EIF = 1.0

    # print("STEP 2")
    # print("A_EIF: very low")
    # print("B_EIF: very high")
    # print("C_EIF: very low")
    # print()

    # STEP 3: ECF calculation
    # ECF for high = 0.3 - [(pointB_ECS - 1)*(0.3/4)] 
    B_ECF = 0.3 - (B_ECS - 1)*(0.3/4)

    # ECF for low = 1.2 - [(pointA,C_ECS - 1)*(1.2/4)] 
    A_ECF = 0.3 - (A_ECS - 1)*(1.2/4)
    C_ECF = 0.3 - (C_ECS - 1)*(1.2/4)

    # print("STEP 3")
    # print("A_ECF: " + str(A_ECF))
    # print("B_ECF: " + str(B_ECF))
    # print("C_ECF: " + str(C_ECF))
    # print()

    # STEP 4: ECI calculation
    # ECI = ECS - ECF
    A_ECI = A_ECS - A_ECF
    B_ECI = B_ECS - B_ECF
    C_ECI = C_ECS - C_ECF

    # print("STEP 4")
    # print("A_ECI: " + str(A_ECI))
    # print("B_ECI: " + str(B_ECI))
    # print("C_ECI: " + str(C_ECI))
    # print()

    # STEP 5: BCS calculation
    # for N = 3 bridge elements (summation)
    BCS_top = (A_ECI*A_EIF) + (B_ECI*B_EIF) + (C_ECI*C_EIF)
    BCS_bot = A_EIF + B_EIF + C_EIF
    BCS = BCS_top/BCS_bot

    # print("STEP 5")
    # print("BCS: " + str(BCS))
    # print()

    # STEP 6: BCI calculation
    print("100 - " + str((2 * (pow(BCS, 2) + (6.5 * BCS) - 7.5))))
    BCI = 100 - (2 * (pow(BCS, 2) + (6.5 * BCS) - 7.5))
    # print("STEP 5")
    print("BCI: " + str(BCI))
    print()

    url = "https://smart-city-266807.appspot.com/bci"
    data = {"id": "0", "bci": BCI, "latitude": 33.714445, "longitude": -117.921869}
    r = requests.post(url = url, json = data)
    # print(r.content)
Пример #59
0
    # Because we are rebuilding in sandbox the pools are always called VM-MIRROR
    #POOL=PROJ["POOL"]
    POOL="VM-MIRROR"

    # Get replication target ID, this needs to be already setup in the BUI
    url = 'https://'+HOST+':215/api/storage/v1/replication/targets'
    response = requests.get(url, headers={'Authorization': 'Basic cm9vdDpHMGRfNGM3Xw=='},verify=False)
    nodeRef = json.loads(response.text)
    # We assume only one target, which should always be the case in our environment
    TARGET = nodeRef['targets'][0]['label']

    # Create the projects and LUNS
    data = { 'name':PROJECT }
    headers = {'Authorization': 'Basic cm9vdDpHMGRfNGM3Xw==', 'Content-Type': 'application/json'}
    url = 'https://'+HOST+':215/api/storage/v1/pools/'+POOL+'/projects'
    response = requests.post(url,headers=headers,data=json.dumps(data),verify=False)
    print 'Created '+PROJECT+' on '+POOL, response
    if response.status_code != 201:
        print json.dumps (response.json(), sort_keys=True, indent=4, separators=(',', ': '))

    # Create LUNS while we are here
    data = { 
        'name':LUN,
        'volsize':500*1024*1024
    }
    url = 'https://'+HOST+':215/api/storage/v1/pools/'+POOL+'/projects/'+PROJECT+'/luns'
    response = requests.post(url,headers=headers,data=json.dumps(data),verify=False)
    #print json.loads(response.text)
    print 'Created '+LUN+' in project '+PROJECT, response
    if response.status_code != 201:
        print json.dumps (response.json(), sort_keys=True, indent=4, separators=(',', ': '))
Пример #60
0
    "塞浦路斯", "尼泊尔", "巴拉圭", "布基纳法索", "乌拉圭", "塞拉利昂", "安道尔", "尼加拉瓜", "格鲁吉亚",
    "埃塞俄比亚", "约旦", "乍得", "钻石号邮轮", "中非共和国", "圣马力诺", "马达加斯加", "马耳他", "刚果(布)",
    "牙买加", "坦桑尼亚", "巴勒斯坦", "多哥", "佛得角", "卢旺达", "毛里求斯", "越南", "黑山", "毛里塔尼亚",
    "乌干达", "斯威士兰", "利比里亚", "也门", "莫桑比克", "贝宁", "缅甸", "蒙古", "文莱", "圭亚那", "津巴布韦",
    "柬埔寨", "叙利亚", "特立尼达和多巴哥", "马拉维", "巴哈马", "利比亚", "摩纳哥", "巴巴多斯", "科摩罗",
    "列支敦士登公国", "安哥拉", "布隆迪", "厄立特里亚", "马提尼克岛", "博茨瓦纳", "不丹", "冈比亚", "安提瓜和巴布达",
    "东帝汶", "格林纳达", "纳米比亚", "老挝", "斐济", "伯利兹", "圣文森特和格林纳丁斯", "圣卢西亚", "多米尼克",
    "圣基茨和尼维斯", "梵蒂冈", "苏里南", "塞舌尔", "巴布亚新几内亚", "莱索托"
]
print("本程序用于拟合所选国家感染人数和预测未来数据")
for i in range(len(country_list)):
    print(str(i) + "." + country_list[i])
print("请选择所想展示的国家(输入数字即可):")
n = int(input())
param = {"country": country_list[n]}
res = requests.post(query_url, param)
d = json.loads(res.content.decode())
data = pd.DataFrame(d['data'])
xs = pd.DataFrame(d['data']).date
for i in range(len(xs)):
    xs[i] = "2020-" + xs[i][0] + xs[i][1] + '-' + xs[i][3] + xs[i][4]
xs = [datetime.strptime(d, '%Y-%m-%d').date() for d in xs]
data.insert(0, 'riqi', xs)
#data.to_csv("tzzs_data.csv")

x = np.arange(1, len(xs) + 1, 1)
y = np.array(data.confirm_add)
z1 = np.polyfit(x, y, 3)  #用n次多项式拟合
p1 = np.poly1d(z1)
print(p1)  #在屏幕上打印拟合多项式
yvals = p1(x)