def _do_async_request(self, url, payload):
		def empty_callback(response):
			pass

		# TODO currently errors when server offline
		# Try catch doesn't work because of threading
		unirest.post(url, headers = {"Accept": "application/json"}, params = payload, callback = empty_callback)
Example #2
0
def process_news(request):
    queryset = article.objects.all()

    emotion = unirest.post("http://apidemo.theysay.io/api/v1/emotion",
                           headers={"Accept": "application/json"},
                           params={
                               "text": "",
                               "level": "sentence"
                           })

    #print emotion.body
    pp = pprint.PrettyPrinter(indent=4)
    pp.pprint(emotion.body)

    topic = unirest.post("http://apidemo.theysay.io/api/v1/topic",
                         headers={"Accept": "application/json"},
                         params={
                             "text": text,
                             "level": "sentence"
                         })

    #print topic.body
    pp.pprint(topic.body)

    sentiment = unirest.post("http://apidemo.theysay.io/api/v1/sentiment",
                             headers={"Accept": "application/json"},
                             params={
                                 "text": text,
                                 "level": "sentence"
                             })

    #print sentiment.body
    pp.pprint(sentiment.body)
def test_predict_recognition():
    set_unirest_defaults()
    first_image_response = unirest.post(hostname + '/enroll-image/',
        params={"image": open("./arnold.jpg", mode="r"), "label":"Arnold Schwarzenegger"})
    print first_image_response.body
    assert first_image_response.code == 200
    training_set_id = first_image_response.body['id']
    second_image_response = unirest.post(hostname + '/enroll-image/',
        params={"image_url": "http://images.politico.com/global/click/101103_schwarznegger_face_ap_392_regular.jpg", "label":"Arnold Schwarzenegger", "training_set_id":training_set_id})
    assert second_image_response.code == 200
    print second_image_response.body
    third_image_response = unirest.post(hostname + '/enroll-image/',
        params={"image_url": "http://www.theepochtimes.com/n2/images/stories/large/2011/02/08/72460251.jpg", 
        "label":"Donald Rumsfeld", "training_set_id":training_set_id})
    assert third_image_response.code == 200
    #check training set
    training_set_response = unirest.get(hostname + '/trainingset/' + training_set_id)
    print training_set_response.body
    face_images = training_set_response.body['face_images']
    assert len(face_images) == 3
    response = unirest.post(hostname + '/compile-training-set/',
        params={"training_set_id":training_set_id})
    print response.body
    predictive_model_id = response.body['id']
    time.sleep(MODEL_COMPILATION_SECONDS)
    prediction_response = unirest.post(hostname + '/recognize-face/',
        params={"predictive_model_id":predictive_model_id, "image_url":"http://img1.wikia.nocookie.net/__cb20130930223832/armoredheroes/images/3/37/Arnold_Schwarzenegger.jpg"})
    print prediction_response.body
    assert prediction_response.code == 200
    assert prediction_response.body['person']['name'] == "Arnold Schwarzenegger"
Example #4
0
 def test_S_SYNC_ENDED_R_LOAD_FILE(self):
     sucess = 1
     res = unirest.post(SERVER_URL + 'loadFile',
                        headers={"Accept": "application/json"},
                        params={
                            "parameter":
                            '{"command": "LOAD_FILE testAudioFile.pcm"}',
                            "file": open("files/testAudioFile.pcm",
                                         mode="r")
                        })
     tmp_res = json.loads(res.raw_body)
     sucess = sucess & (tmp_res['success'] == True)
     sucess = sucess & (tmp_res['data'] == "FILE_FOUND_AND_LOADED")
     res = unirest.post(SERVER_URL + 'loadFile',
                        headers={"Accept": "application/json"},
                        params={
                            "parameter":
                            '{"command": "LOAD_FILE testAudioFil.pcm"}',
                            "file": open("files/testAudioFile.pcm",
                                         mode="r")
                        })
     tmp_res = json.loads(res.raw_body)
     sucess = sucess & (tmp_res['success'] == False)
     sucess = sucess & (tmp_res['data'] == "FILE_NOT_FOUND")
     time.sleep(0.2)
     self.assertEqual(sucess, 1)
Example #5
0
def loop_script():
    for i in coin_pairs:
        breakout = findBreakout(coin_pair=i, period=5, unit="fiveMin")
        sma = calculateSMA(coin_pair=i, period=5, unit="fiveMin")
        ema = calculateEMA(coin_pair=i, period=5, unit="fiveMin")
        rsi = calculateRSI(coin_pair=i, period=14, unit="thirtyMin")
        baseLine = calculateBaseLine(coin_pair=i, unit="day")
        conversionLine = calculateConversionLine(coin_pair=i, unit="day")
        leadSpanA = calculateLeadingSpanA(coin_pair=i, unit="day")
        leadSpanB = calculateLeadingSpanB(coin_pair=i, unit="day")
        closingPrices = getClosingPrices(coin_pair=i,
                                         period=14,
                                         unit='thirtyMin')
        rangeClosingPrices = getRangeClosingPrices(coin_pair=i,
                                                   period_from=1,
                                                   period_to=14,
                                                   unit='thirtyMin')

        print("{} ======================".format(i))
        print("Breakout: {}".format(breakout))
        print("RSI: {}".format(rsi))
        print("SMA: {}".format(sma))
        print("EMA: {}".format(ema))
        print(
            "Ichimoku: BaseLine: {} ConversionLine: {} LeadSpanA: {} LeadSpanB: {}"
            .format(baseLine, conversionLine, leadSpanA, leadSpanB))
        print("Closing Price: {}".format(map(str, closingPrices)))
        print("Closing Price: {}".format(map(str, rangeClosingPrices)))
        if (rsi >= 55.0 or rsi <= 45.0):
            # unirest.post("https://coinwatch-demo.herokuapp.com/alert", params={
            #     "type": "RSI",
            #     "value": rsi,
            #     "pair": i,
            # }, callback=webhookCallback)
            print("PERFORM POST")
            type = "sell" if rsi >= 55.0 else "buy"
            current_price = my_bittrex.get_ticker(i)
            unirest.post(
                os.getenv("TRADE_POST_URL"),
                params={
                    "trade": {
                        "transaction_type": type,
                        "pair": i,
                        "amount_ratio": 0.1,
                        "current_price": {
                            "bid": current_price['result']['Bid'],
                            "ask": current_price['result']['Ask']
                        },
                        "bittrex_key": os.getenv("ENCRYPTED_BITTREX_KEY"),
                        "bittrex_secret":
                        os.getenv("ENCRYPTED_BITTREX_SECRET"),
                        "limit_order":
                        False,  # TODO: set True to live trade on Bittrex
                        "comment": "Sample Text"
                    }
                },
                auth=(os.getenv("USER_EMAIL"), os.getenv("USER_PASSWORD")))
        else:
            print("No Webhook")
Example #6
0
 def send_message(self):
     params = {'to': self.to, 'data': self.data}
     params = JSONRenderer().render(params)
     print params
     unirest.post(url,
                  headers=headers,
                  params=params,
                  callback=self.callback)
Example #7
0
def send_sync_data(host_list, data, rest_interface):
    print "send_sync_data: start sync data.."
    data_json = json.dumps(data)
    header = {'Content-Type': 'application/json'}
    for cloud in host_list:
        if host_list[cloud][0]:
            host_url = "http://" + host_list[cloud][1] + rest_interface
            print "send_sync_data: host URL: " + host_url + " "
            unirest.post(host_url, headers=header, params=data_json, callback=unirest_callback)
Example #8
0
def deleteTopup(tid, callback):
    data = {}
    data['tid'] = tid
    data = json.dumps(data)
    unirest.post(damadam_url + "/api/ad/delete/",
                 headers={"Content-type": "application/json"},
                 params=data,
                 auth=(damadam_user, damadam_pass),
                 callback=callback)
    def _do_async_request(self, url, payload):
        def empty_callback(response):
            pass

        # TODO currently errors when server offline
        # Try catch doesn't work because of threading
        unirest.post(url,
                     headers={"Accept": "application/json"},
                     params=payload,
                     callback=empty_callback)
Example #10
0
def found_pop(*args, **kwargs):
    """

    :param args:
    :param kwargs:
    :return:
    """

    url = urljoin(server_addr, make_ext)
    if 'commands' in kwargs:
        url = urljoin(url, "?" + urlencode(kwargs['commands']))
    print unirest.post(url)
Example #11
0
def send_sync_data(host_list, data, rest_interface):
    print "send_sync_data: start sync data.."
    data_json = json.dumps(data)
    header = {'Content-Type': 'application/json'}
    for cloud in host_list:
        if host_list[cloud][0]:
            host_url = "http://" + host_list[cloud][1] + rest_interface
            print "send_sync_data: host URL: " + host_url + " "
            unirest.post(host_url,
                         headers=header,
                         params=data_json,
                         callback=unirest_callback)
Example #12
0
 def getAuth(self, email, password):
     """Enter your email and password for oc.tc.
     If you don't feel comfortable doing this,
     follow the instructions in AUTHTUTORIAL.md
     to get your auth token."""
     self.return_code = unirest.post(join('http://', self.url, 'players', 'auth'),
         headers={"Content-Type":"application/json", "Authorization":"Basic","Accept":"application/json"},
         params=json.dumps({"email":"{0}".format(email),"password":"******".format(password)})).code
     checkCode(self.return_code)
     return str(unirest.post(join('http://', self.url, 'players', 'auth'),
         headers={"Content-Type":"application/json", "Authorization":"Basic","Accept":"application/json"},
         params=json.dumps({"email":"{0}".format(email),"password":"******".format(password)})).body['token'])
Example #13
0
    def __imageUpload(self,img,url=False):
        """
        Uploads an image to the camfind api hosted on mashape
        Returns a string token which can be used to retrieve the recognized objects
        
        Parameters
        ----------
        img: file or url
          An image file or url pointing to an image, such as jpeg, to pass to the api

        url: string
          If url is True, the img argument will be interpreted as a url
          instead of a binary image file
        """

        if url == True:
            #configure headers to read an image from an uploaded url
            response = unirest.post("https://camfind.p.mashape.com/image_requests",
              headers={
                "X-Mashape-Key": self.getApiKey(),
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json"
              },
              params={
                "image_request[remote_image_url]": img,
                "image_request[altitude]": "27.912109375",
                "image_request[language]": "en",
                "image_request[latitude]": "35.8714220766008",
                "image_request[locale]": "en_US",
                "image_request[longitude]": "14.3583203002251",
              }
            )

        else:
            #configure headers to read an image from local upload
            response = unirest.post("https://camfind.p.mashape.com/image_requests",
              headers={
                "X-Mashape-Key": self.getApiKey(),
              },
              params={
                "image_request[image]": open(img, mode="r"),
                "image_request[altitude]": "27.912109375",
                "image_request[language]": "en",
                "image_request[latitude]": "35.8714220766008",
                "image_request[locale]": "en_US",
                "image_request[longitude]": "14.3583203002251",
              }
            )

        print(response.body)
        return response.body["token"]
Example #14
0
    def setup(self, callback):
        """
            Setup Github project repository.

            Args:
                callback (function): POST request callback function
        """
        params = {'name': self._project_name}
        query = {'access_token': self._access_token}

        unirest.post("{}/user/repos?{}".format(self._github_api_url,
                                               urlencode(query)),
                     params=json.dumps(params),
                     callback=callback)
Example #15
0
    def setup(self, callback):
        """
            Setup Bitbucket project repository.

            Args:
                callback (function): POST request callback function
        """

        # configure the project repository
        data = {'name': self._project_name, 'is_private': True}
        unirest.post(url="{}/repositories".format(self._bitbucket_api_url),
                     auth=(self._bitbucket_username, self._bitbucket_password),
                     params=data,
                     callback=callback)
Example #16
0
def test_enroll_image_in_existing_training_set():
    first_image_response = unirest.post(hostname + '/enroll-image/',
        params={"image": open("./arnold.jpg", mode="r"), "label":"Arnold"})
    assert first_image_response.code == 200
    print first_image_response.body
    training_set_id = first_image_response.body['id']
    second_image_response = unirest.post(hostname + '/enroll-image/',
        params={"image": open("./arnold.jpg", mode="r"), "label":"Arnold", "training_set_id":training_set_id})
    assert second_image_response.code == 200
    print second_image_response.body
    #check training set
    training_set_response = unirest.get(hostname + '/trainingset/' + training_set_id + '/')
    print training_set_response.body
    face_images = training_set_response.body['face_images']
    assert len(face_images) == 2
Example #17
0
def nlp_call():
    #text processing NLP call
    response = unirest.post(
        "https://japerk-text-processing.p.rapidapi.com/sentiment/",
        headers={
            "X-RapidAPI-Host": "japerk-text-processing.p.rapidapi.com",
            "X-RapidAPI-Key":
            "1cb24d07fdmsh0a4062c072f1dbdp164f8cjsn1c8a66bfc2fd",
            "Content-Type": "application/x-www-form-urlencoded"
        },
        params={
            "language":
            "english",
            "text":
            "How much damage does heroin do to the brain and how addictive is it?"
        })
    for i in response.body['probability']:
        print(response.body['probability'][i])

    #microsoft NLP call
    response2 = unirest.post(
        "https://microsoft-azure-text-analytics-v1.p.rapidapi.com/sentiment",
        headers={
            "X-RapidAPI-Host":
            "microsoft-azure-text-analytics-v1.p.rapidapi.com",
            "X-RapidAPI-Key":
            "1cb24d07fdmsh0a4062c072f1dbdp164f8cjsn1c8a66bfc2fd",
            "Content-Type": "application/json"
        },
        params=
        ("{\"documents\":[{\"language\":\"en\",\"id\":\"string\",\"text\":\"How much damage does heroin do to the brain and how addictive is it? \"}]}"
         ))
    print("microsoft: ", response2.body['documents'][0]['score'])
    if (response2.body['documents'][0]['score'] < 1):
        print("hello")

    #Amazon NLP call
    comprehend = boto3.client(service_name='comprehend',
                              region_name='us-east-2')

    text = "It is raining today in Seattle"

    print('Calling DetectSentiment')
    print(
        json.dumps(comprehend.detect_sentiment(Text=text, LanguageCode='en'),
                   sort_keys=True,
                   indent=4))
    print('End of DetectSentiment\n')
Example #18
0
def get_main_emotion_from_image():

    command = "ffmpeg -i new.mov -vcodec png -ss 2 -vframes 1 -an -f rawvideo video.png"
    subprocess.call(command, shell=True)

    response = unirest.post("https://eyeris-emovu1.p.mashape.com/api/image/",
                            headers={"X-Mashape-Key": "ENTER_YOUR_API_KEY"},
                            params={"imageFile": open("video.png", mode="r")})

    data = response.body

    dataset = data["FaceAnalysisResults"][0]["EmotionResult"]

    try:
        del dataset["Computed"]
    except KeyError:
        pass

    max = 0
    for i in dataset:
        if float(dataset[i]) > max:
            max = float(dataset[i])
            val = i

    os.remove('video.png')

    return val
Example #19
0
def identify_image(inputFileURL):
    response = unirest.post("https://camfind.p.mashape.com/image_requests",
  headers={
    "X-Mashape-Key": "9UyIuOYhCKmshb72Y27ctmWYJReGp1G3LaBjsndZ3QPhPjjHMl"
  },
  params={
    "focus[x]": "480",
    "focus[y]": "480",
    "image_request[language]": "en",
    "image_request[locale]": "en_US",
    "image_request[remote_image_url]": ""+str(inputFileURL)+""
  }
)

    token = response.body['token'] # The parsed response
    print token
    response2 = unirest.get("https://camfind.p.mashape.com/image_responses/"+str(token),
  headers={
    "X-Mashape-Key": "9UyIuOYhCKmshb72Y27ctmWYJReGp1G3LaBjsndZ3QPhPjjHMl"
  }
)
    time.sleep(1)
    while (response2.body['status'] == 'not completed'):
        response2 = unirest.get("https://camfind.p.mashape.com/image_responses/"+str(token),
    headers={
        "X-Mashape-Key": "9UyIuOYhCKmshb72Y27ctmWYJReGp1G3LaBjsndZ3QPhPjjHMl"
    }
    )
    print "Sleeping"
    time.sleep(1)

    #print response2.body
    print response2.raw_body
Example #20
0
def describeImage(imgPath):
	response = unirest.post("https://camfind.p.mashape.com/image_requests",
	  headers={
	    "X-Mashape-Key": "You meshape key, register at meshape https://market.mashape.com/imagesearcher/camfind"
	  },
	  params={
	    "image_request[image]": open(imgPath, mode="r"),
	    "image_request[language]": "en",
	    "image_request[locale]": "en_US"
	  }
	)
	
	token=response.body['token']
	
	response = unirest.get("https://camfind.p.mashape.com/image_responses/" + token,
	  headers={
	    "X-Mashape-Key": "aiYZkTIXj7mshNul9uy1GrEoIZYOp1QdFbGjsn3AexvpbfgD3g",
	    "Accept": "application/json"
	  }
	)
	
	while (response.body['status']!="completed" and response.body['status']!="skipped"):
		time.sleep(1) #sleep for 1 seconds
		response = unirest.get("https://camfind.p.mashape.com/image_responses/" + token,
		  headers={
		    "X-Mashape-Key": "aiYZkTIXj7mshNul9uy1GrEoIZYOp1QdFbGjsn3AexvpbfgD3g",
		    "Accept": "application/json"
		  }
		)
	
	#assume completed
	if (response.body['status']!="skipped"):
		return response.body['name']
	else:
		return "unsuccessful"
Example #21
0
    def test_add_film_normal(self):
        sucess = 1
        for film in data_in_json_format['film']:
            film_name = "_".join(film['name'].split())
            film_name += "_"

            res = unirest.post(
                SERVER_URL + 'addFilm',
                headers={"Accept": "application/json"},
                params={
                    "parameter":
                    '{  "name": "' + film['name'] + '" , "duration_hour": ' +
                    str(film['duration_hour']) + ' , "duration_minute": ' +
                    str(film['duration_minute']) + ' , "description": "' +
                    film['description'] + '" , "initial_language": "' +
                    film['initial_language'] + '" , "translated_language": "' +
                    film['translated_language'] + '"}',
                    "file":
                    open("files/" + film_name + film['initial_language'],
                         mode="r")
                })
            tmp = {}
            tmp_res = json.loads(res.raw_body)
            sucess = sucess & (tmp_res['success'] == True)
        self.assertEqual(sucess, 1)
Example #22
0
	def _post(self, endpoint, query):
		"""
		Send a POST to the exchange.

		:param str endpoint:
		:param str query:
		:returns result:
		"""
		url = self._BASE_URL + endpoint + query

		print url

		idx = query.find('clientOrderId')
		if idx == -1:
			raise APIError('something bad happened')
		else:
			params = query[idx:]

		print params
	
		signature = hmac.new(self._secret, endpoint + query, hashlib.sha512).hexdigest()

		idx2 = url.find('clientOrderId')
		if idx2 == -1: raise ValueError('poop!')

		url = url[:idx2 - 1]

		print 'url', url
		print 'sig', signature
		print 'params', params
		result = unirest.post(url, headers={"Api-Signature": signature}, params=params)

		return result
	def test_post(self):
		response = unirest.post('http://httpbin.org/post', params={"name":"Mark", "nick":"thefosk"})
		self.assertEqual(response.code, 200)
		self.assertEqual(len(response.body['args']), 0)
		self.assertEqual(len(response.body['form']), 2)
		self.assertEqual(response.body['form']['name'], "Mark")
		self.assertEqual(response.body['form']['nick'], "thefosk")
Example #24
0
    def getMetacriticAttr(self):
        try:
            response = unirest.post("https://byroredux-metacritic.p.mashape.com/find/game",

                                    headers = {
                                        "X-Mashape-Authorization": ""
                                    },
                                    params = {
                                        "title": self.productname,
                                        "platform": self.METACRITICPLATFORMDICTIONARY[self.consolename]
                                    }
            );

            d = json.loads(json.dumps(response.body))

            d = d['result']

            self.score = int(d[r'score'])
            self.rating = d[r'rating']
            self.publisher = d[r'publisher']
            self.developer = d[r'developer']
        except:
            self.score = None
            self.rating = None
            self.publisher = None
            self.developer = None
Example #25
0
    def create(email, password, first_name=None, last_name=None):
        """Creates a new user in the signnow system.

        Args:
            email (str): The email of the new user you want to create (It can not already exist in the system).
            password (str): The password for the new user you are creating.
            first_name (str): An optional argument that represents the first name of the new user.
            last_name (str): An optional argument that represents the last name of the new user.

        Returns:
            dict: A dictionary representing the JSON response for the created user API or error returned.
        """
        request = post(Config().get_base_url() + '/user',
                       headers={
                           "Authorization":
                           "Basic " + Config().get_encoded_credentials(),
                           "Accept":
                           "application/json",
                           "Content-Type":
                           "application/json"
                       },
                       params=dumps({
                           "email": email,
                           "password": password,
                           "first_name": first_name,
                           "last_name": last_name
                       }))

        return request.body
Example #26
0
def generate(request):
    url = request.GET.get('url', '')

    # check cache
    if url not in cache:
        # service call to phishtank
        response = unirest.post(
            "http://checkurl.phishtank.com/checkurl/",
            params={
                "app_key": "df0bbae9d44d378c5c86df29628a41142d61ee8dd275808fe6e0b11972e62bf5",
                "url": base64.b64encode(url),
                "format": "json",
            },
        )

        # check if it's a phish site, if not, create short_url
        if not response.body["results"]["in_database"]:
            short_url = ShortUrl.objects.create_url(url)
            response.body['url_hash'] = short_url.url_hash
        else:
            response.body['url_hash'] = "PHISHING_SITE"

        # set cache
        cache.set(url, response)
        response.body['cached'] = False

    else:
        # url has already been checked
        response = cache.get(url)
        response.body['cached'] = True

    return HttpResponse(json.dumps(response.body), content_type="application/json")
Example #27
0
def square():

    # Sandbox Location ID (Coffee & Toffee NYC)
    card_nonce = 'CBASEK7szS0c9dWDBehyyEiwnJQgAQ'
    if request.form:
        card_nonce = request.form
        print("card nonce: ", card_nonce)
    location_id = 'CBASEEKdEq0dwQd9aigzQlUVGhYgAQ'
    #card_nonce =

    items = [{"total": i.sold * i.price} for i in session.query(Item).all()]

    response = unirest.post('https://connect.squareup.com/v2/locations/' +
                            location_id + '/transactions',
                            headers={
                                'Accept': 'application/json',
                                'Content-Type': 'application/json',
                                'Authorization':
                                'Bearer ' + square_access_token,
                            },
                            params=json.dumps({
                                'card_nonce':
                                card_nonce,
                                'amount_money': {
                                    'amount': int(100 + items[0]['total']),
                                    'currency': 'USD'
                                },
                                'idempotency_key':
                                str(uuid.uuid1())
                            }))

    return json.dumps(response.body)
	def set_flow(self, dpid, inPort, srcMac, dstMac):
		header = {'Content-type':'application/json'}
		body = {'dpid':"{:0>16x}".format(dpid), 'inPort':inPort, 'srcMac':srcMac, 'dstMac':dstMac}
		LOG.debug("body = " + str(body))
		LOG.info("Request setFlow body = " + str(body))
		res = unirest.post(CONF.ofpm_set_flow_url, headers=header, params=str(body), callback=self.__http_response__)
		return 
Example #29
0
def getIngredientsFromString(string):
    """
	A function to call the spoonacular API to grab the ingredience from a string
	"""

    # making Spoonacular API call
    response = unirest.post(
        "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/food/detect",
        headers={
            "X-Mashape-Key": SPOONACULAR_API_KEY,
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "application/json"
        },
        params={"text": string})

    # grabbing the data produced by the API call
    b = response.raw_body
    # loading data into a json format
    b_json = json.loads(b)
    # dictonary to hold the outgoing items for the json file
    ingredients = {}
    # start the correct tagging
    ingredients["ingredients"] = []
    # parse the given JSON file recieved from spoonacular
    for i in range(len(b_json["annotations"])):
        ingredients["ingredients"].append(
            b_json["annotations"][i]["annotation"])
    # putting the extracted data into a json file
    with open("JSON_Files/ingredientsFromString.json", "w") as f:
        json.dump(ingredients, f, indent=1)
def plot_wordcloud(data):
	# Test data
	# data = ['You','you','hate','peanuts','because','you','are','allergic','Why','did','you','eat','the','jam','jam','is','poisonous','to','peanuts']

	textblock = ""
	for i in range(0, len(data)):
		#if i>0 :
		#	textblock += " "
		textblock += data[i]
	height = 1000
	width = 800
	config = "n/a"

	print textblock
	print width
	print height
	print config

	response = unirest.post("https://gatheringpoint-word-cloud-maker.p.mashape.com/index.php",
	  
	  headers={
	  # your mashape API key here
		"X-Mashape-Authorization": "********************"
	  },
	  params={ 
		"height": height,
		"textblock": textblock,
		"width": width,
		"config": config
	  }
	);

	print response.body['url']
	webbrowser.open(response.body['url'])
    def postInsertCustomers(self,):
        '''
        Insert one or more objects

        :returns: response from the API call
        :rType: CustomersModel 
        '''
    
        #prepare query string for API call
        queryBuilder = Configuration.BASEURI + "/Customers"

        #validate and preprocess url
        queryUrl = APIHelper.cleanUrl(queryBuilder)

        #prepare headers
        headers = {
            "User-Agent" : "APIMATIC 2.0",
            "Accept" : "application/json",
        }

        #prepare and invoke the API call request to fetch the response
        response = unirest.post(queryUrl, headers=headers)

        #Error handling using HTTP status codes
        if response.code < 200 and response.code > 206: #200 = HTTP OK
            raise APIException("HTTP Response Not OK", response.code)     

        return response.body
Example #32
0
	def text_processing(self,data):
		response = unirest.post("http://text-processing.com/api/sentiment/",
			headers={
				"X-Mashape-Key": "DN4Pvj9aQvmshoeibOcMLVzHMb6yp19PYoqjsnTwnkoVOF5jzD",
				"Content-Type": "application/x-www-form-urlencoded",
				"Accept": "application/json"
			},
			params={
				"language": "english",
				"text": data
			}
		)
		resp = response.body['probability']
		minimo = min(resp)
		maximo = max(resp)
		print '/********** API text_processing **********/'
		print 'Respuesta JSON: ',resp
		print 'Porc Min: ',minimo,'',resp[minimo]
		print 'Porc Max: ',maximo,'',resp[maximo]
		if maximo == 'neg':
			respuesta = 'Emocion Negativa'
		elif maximo == 'neutral':
			respuesta = 'Emocion Neutral'
		else:
			respuesta = 'Emocion Positiva'
		print 'Respuesta Analisis: ',respuesta
		print '/********** FIN API text_processing **********/\n'
		#respuesta = json.dumps({maximo:resp[maximo]})

		return respuesta
Example #33
0
 def post_txt_file(self,grp,file_o):
   response = unirest.post("https://api.ciscospark.com/v1/messages/", 
     headers={
       "Authorization": hard_key,
       "Content-Type": "application/json"},
     params=json.dumps({"roomId":grp,"files":["https://secret-brushlands-95547.herokuapp.com/txt/"+file_o]})
   )  
Example #34
0
	def send_new_order(self, symbol, side, price, quantity, order_type='limit', tif='IOC'):
		"""
		Send a new market limit order to the exchange.

		:param str symbol: BTCUSD
		:param str side: buy or sell
		:param float price: 
		:param int quantity:
		:param str order_type:
		:param str tif:
		:returns ExecutionReport:
		"""
		if not self._key and self._secret:
			raise AuthenticationError('A valid provisioned API key and secret are required to send orders')

		nonce = HitBTC.construct_nonce()
		clorid = ''.join(random.choice(string.digits + string.ascii_lowercase) for _ in range(30))
		path = "/api/1/trading/new_order?apikey=" + self._key + "&nonce=" + nonce
		new_order = "clientOrderId=" + clorid + "&symbol=%s&side=%s&price=%s&quantity=%s&type=%s&timeInForce=%s" % (symbol, side, price, quantity, order_type, tif)

		signature = hmac.new(self._secret, path + new_order, hashlib.sha512).hexdigest()

		result = unirest.post("http://demo-api.hitbtc.com" + path, headers={"Api-Signature": signature}, params=new_order)
		
		return result
Example #35
0
def send_precision_recall_data(test_datapoints, valid_datapoints, job_id=None):
    if not job_id:
        job_id = current_id
    url = base_url + "job/" + job_id + "/precision-recall-curve"
    def callback(response):
        print(response.body)
    thread = unirest.post(url, headers=default_headers, params=json.dumps({"test": test_datapoints, "valid": valid_datapoints}), callback=callback)
Example #36
0
def generic(query):
    """ generic(query) -- process a generic user query using the Stanford 
	NLTK NER and duckduckgo api.
	"""

    try:
        response = unirest.post(
            "https://textanalysis.p.mashape.com/nltk-stanford-ner",
            headers={
                "X-Mashape-Key": "E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP",
                "Content-Type": "application/x-www-form-urlencoded",
            },
            params={"text": query},
        )
    except:
        print "Unable to connect to internet"
        return
    web_query = ""
    for entity in response.body["result"].split():
        word, tag = entity.split("/")
        if tag != "O":
            web_query += " " + word
    if web_query != "":
        web_query = web_query.strip().split()
        duckduckgo.query(web_query)
    else:
        print "I do not know how to process this query at this moment."
Example #37
0
def post(image, sort_type, palette):
    '''

    :param image: image path for sending to colorTag API.
    :param sort_type: supported sort types : relevance and weight.
    :param palette: supported palettes : simple, w3c and precise.
    :return: response body in json format.

    '''

    # replace key value after 500 requests.

    key = ""

    unirest.clear_default_headers()

    response = unirest.post(
        "https://apicloud-colortag.p.mashape.com/tag-file.json",
        headers={"X-Mashape-Key": key},
        params={
            "image": open(image, mode="r"),
            "palette": palette,
            "sort": sort_type
        })

    logging.info('resoponse code for image: ' + str(image) + ' is: ' +
                 str(response.code))

    return response.raw_body
Example #38
0
def fetch_daily_service_monitoring_rate(access_token, appId):
    response = unirest.post(
        "https://developers.crittercism.com:443/v1.0/performanceManagement/pie",
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer %s" % access_token,
        },
        params=json.dumps({
            "params": {
                "groupBy": "service",
                "graph": "errors",
                "duration": 60,
                "appId": appId
            }
        }))
    service_list = []
    try:
        for service in response.body['data']['slices']:
            service_list.append((service['label'], service['value']))
        service_list = sorted(service_list, key=lambda x: x[1],
                              reverse=True)[0:4]
        return map(list, zip(*service_list))
    except KeyError as e:
        print 'ERROR: Could not access %s in %s.' % (
            str(e), 'fetch_daily_service_monitoring_rate')
        return [None, None]
def push_daily_crashes_os(os_list):
	response = unirest.post(
		"https://push.geckoboard.com/v1/send/106305-941b1040-d241-4106-a78e-6603c2a29a53",
		headers={"Accept": "application/json", "Content-Type": "application/json"},
		params=json.dumps({
		  "api_key": geckoboard_key,
		  "data": {
  	"item": [
 	   {
 	     "value": os_list[1][0], #os one value
 	     "label": os_list[0][0], #os name
 	   },
 	   {
 	     "value": os_list[1][1], #os two value
 	     "label": os_list[0][1], #os name
 	   },
 	   {                                                                                                                                              
 	     "value": os_list[1][2], #os three value                                                                                                                       
 	     "label": os_list[0][2], #os name                                                                                                                            
 	   },  
 	   {                                                                                                                                              
    	  "value": os_list[1][3], #os three value                                                        
    	  "label": os_list[0][3], #os name                                                                                                                           
    	}  
  	]
	}}))
Example #40
0
def __rest_call(method, request):
    response = ""

    request_url = request.get("url")
    # The second parameter in the get means that if "headers" is not in the dictionary,
    # set the variable to DEFAULT_HEADERS.
    request_headers = request.get("headers", DEAFAULT_HEADERS)

    if (method == POST):
        response = unirest.post(request_url,
                                headers=request_headers,
                                params=request.get("params"))
    elif (method == GET):
        response = unirest.get(request_url)

    # We want to make sure we get some sort of 200 back (200 is a success for
    # an http request)
    print "-----------------------------------------------------------------------"
    if (response.code / 2 != 100):
        print "ERROR: Recieved %s for a %s request to %s" % (str(
            response.code), method, request.get("url"))
    else:
        print "SUCCESS: Recieved %s for a %s request to %s" % (str(
            response.code), method, request.get("url"))

    print "Response body: " + str(response.body)
    print "-----------------------------------------------------------------------"
Example #41
0
	def ofc_flow_stats_request(self, req):
		header = {'Content-type':'application/json'}
		try:
			res = unirest.post(stats_cfg.ofc_url + stats_cfg.ofc_flow_stats_url, headers=header, params=req, callback=self.__http_response__)
		except e:
			LOG.exception(e.message)
		return res
Example #42
0
def get_data(tweets_data):
	f = open("tweet_data.csv", 'wt')
	writer = csv.writer(f)
	writer.writerow( ('Tweet-Text', 'Tweet-Lang', 'Tweet-country', 'sentiment_type', 'sentiment_score', 'sentiment_result_code', 'sentiment_result_msg') )
	for tweets in tweets_data:
		tweet_text = tweets['text'].encode('ascii', 'ignore')
		response = unirest.post("https://twinword-sentiment-analysis.p.mashape.com/analyze/",
			headers={"X-Mashape-Key": "sGskCbyg1kmshjbTFyTlZCsjHv4vp1MGPV8jsnB1Qfk2Y8Q5Nt",
			"Content-Type": "application/x-www-form-urlencoded",
			"Accept": "application/json"
			},params={"text": tweet_text})
		response_body = response.body
		response_type = response_body['type'].encode('ascii', 'ignore')
		print response_type
		response_score = response_body['score']
		response_result_code = response_body['result_code'].encode('ascii', 'ignore')
		response_result_msg = response_body['result_msg'].encode('ascii', 'ignore')
		sentiment_type.append(response_type)
		sentiment_score.append(response_score)
		sentiment_result_code.append(response_result_code)
		sentiment_result_msg.append(response_result_msg)
		tweet_lang = tweets['lang'].encode('ascii', 'ignore')
		tweet_country = tweets['place']['country'].encode('ascii', 'ignore') if tweets['place'] != None else None
		writer.writerow((tweet_text, tweet_lang, tweet_country, response_type, response_score, response_result_code, response_result_msg) )
	f.close()
	pass
Example #43
0
def main():

    search_str = sys.argv[1]
    search_url = search_url1 + search_str + search_url2
    movie_ID_list = []
    pair = []
    calls = 0

    #movie_ID_name
    movie_ID_name_csv.write("Id,Label\n")
    for i in range(1, 2):
        if (calls == 4):
            time.sleep(1)
        response = urllib.urlopen(search_url + str(i))
        calls = (calls + 1) % 5
        data = json.loads(response.read())
        #print data["movies"][0]["title"]

        for movie in data["movies"]:
            movie_ID_name.write(movie["id"] + "," + movie["title"] + "\n")
            movie_ID_name_csv.write(movie["id"] + "," + movie["title"] + "\n")
            movie_ID_list.append(movie["id"])

    #movie_ID_sim_movie_ID
    movie_ID_sim_movie_ID_csv.write("Source,Target,Type\n")
    for movie_id in movie_ID_list:
        if (calls == 4):
            time.sleep(1)
        response = urllib.urlopen(rev_url1 + movie_id + rev_url2)
        calls = (calls + 1) % 5
        data = json.loads(response.read())
        #print data
        #print len(data["reviews"])

        #payload = {'text': 'great'}
        #print requests.get("http://text-processing.com/api/sentiment/", params=payload)

        response = unirest.post(
            "https://community-sentiment.p.mashape.com/text/",
            headers={
                #"X-Mashape-Key": "T3tFQ83dN8mshWpwly2PCqiJup2Ip1NhiSyjsnTVS0Emgy5PBn",
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json"
            },
            params={"txt": "Today is  a good day"})
        # print response.body
        print data["reviews"][45].keys()
        #print data["reviews"][1]["quote"]
        myt = data["reviews"][45]["quote"]
        #result_str = str(subprocess.check_output(),shell=True)#.replace("'", "\"")
        command = "curl -d \"text=" + myt + "\" http://text-processing.com/api/sentiment/"
        p = subprocess.Popen(shlex.split(command),
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        print simplejson.loads(p.stdout.read())
        #print "char:",result_str[1:]
        #result = json.loads("{\"probability\": {\"neg\": 0.091062927148137796, \"neutral\": 0.18765261280477863, \"pos\": 0.9089370728518622}, \"label\": \"pos\"}")
        #result = simplejson.loads((result_str.strip("'<>() ").replace('\'', '\"')))
        #print result_str#["probability"]["neg"]
        """for movie in data["movies"]:
Example #44
0
def get_data(tweets_data):
	f = open("tweet_data.csv", 'wt')
	writer = csv.writer(f)
	writer.writerow( ('Tweet-Text', 'Tweet-Lang', 'Tweet-country', 'sentiment_type', 'sentiment_score', 'sentiment_result_code', 'sentiment_result_msg') )
	for tweets in tweets_data:
		tweet_text = tweets['text'].encode('ascii', 'ignore')
		response = unirest.post("https://twinword-sentiment-analysis.p.mashape.com/analyze/",
			headers={"X-Mashape-Key": "sGskCbyg1kmshjbTFyTlZCsjHv4vp1MGPV8jsnB1Qfk2Y8Q5Nt",
			"Content-Type": "application/x-www-form-urlencoded",
			"Accept": "application/json"
			},params={"text": tweet_text})
		response_body = response.body
		response_type = response_body['type'].encode('ascii', 'ignore')
		print response_type
		response_score = response_body['score']
		response_result_code = response_body['result_code'].encode('ascii', 'ignore')
		response_result_msg = response_body['result_msg'].encode('ascii', 'ignore')
		sentiment_type.append(response_type)
		sentiment_score.append(response_score)
		sentiment_result_code.append(response_result_code)
		sentiment_result_msg.append(response_result_msg)
		tweet_lang = tweets['lang'].encode('ascii', 'ignore')
		tweet_country = tweets['place']['country'].encode('ascii', 'ignore') if tweets['place'] != None else None
		writer.writerow((tweet_text, tweet_lang, tweet_country, response_type, response_score, response_result_code, response_result_msg) )
	f.close()
	pass
Example #45
0
def results():
    text = request.args.get('jsdata')

    if text:  #if text
        similar = []

        for submission in submissions:
            if submission['info'] != '':
                response = unirest.post(
                    "https://twinword-text-similarity-v1.p.mashape.com/similarity/",
                    headers={
                        "X-Mashape-Key":
                        "yl3VcenMlfmshPcSaR0A21BJS82Sp1Mvq8LjsnkzSXBXvwXfVg",
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Accept": "application/json"
                    },
                    params={
                        "text1": text,
                        "text2": submission['info']
                    })

                if response.body['similarity'] > 0.3:
                    similar.append(submission)

        return json.dumps(similar)
Example #46
0
    def __init__(self, url=None):
        if url:
            # retrieve with post method, put for create, get for read, delete for delete
            # unvisitedurls http://localhost:5000/unvisitedurls?start=0&offset=10&spider=douban
            unirest.timeout(180)
            req = unirest.post(url, headers={"Accept":"application/json"})
            self.start_urls = [data['url'] for data in req.body['data']]
            self.name = url[url.find('spider=')+7:]

            self.visitedurldict = OrderedDict()
            self.datadict       = OrderedDict()
            self.filedict       = OrderedDict()
            self.deadurldict    = OrderedDict()

            self.visitedurldict['urls'] = []
            self.datadict['datas']      = []
            self.filedict['files']      = []
            self.deadurldict['urls']    = []

            rules = (
                Rule(sle(allow=("http://book.douban.com/isbn/\d+$")), callback="parse", follow=True),
                Rule(sle(allow=("http://book.douban.com/subject/\d+$")), callback="parse", follow=True),
            )
        # def __del__(self) work
        dispatcher.connect(self.spider_closed, signals.spider_closed)
Example #47
0
def handleQuote(msg, chatID, bot):

	# Handle commands issued with no arguments
	try:
		text = msg["text"].split(' ',1)[1]
	except:
		text = ""
	
	# No arguments: Random between famous and movis
	if text == "":
		category = random.choice(["famous","movies"])
	# Specified famous
	elif text.upper() == "FAMOUS":
		category = "famous"
	# Specified movies
	elif text.upper() == "MOVIES":
		category = "movies"
	# Strings doesn't match valid arguments. Random argument generated.
	else:
		category = random.choice(["famous","movies"])
		
	# Fetch random quote
	response = unirest.post("https://andruxnet-random-famous-quotes.p.mashape.com/?cat="+category,headers={"X-Mashape-Key": "DuskHHYl5DmshhsjvJ4LaVXZinfpp1KnC92jsndIqrz6pC0CDa","Content-Type": "application/x-www-form-urlencoded","Accept": "application/json"}).body
	
	quote = response["quote"]
	author = response["author"]
	message = quote + "\n" + " - " + author
	bot.sendMessage(chatID, message)
Example #48
0
    def request_token(username, password, scope="*"):
        """Request a new oauth2 token from the Signnow API using unirest

        Args:
            username (str): The email of user you want to create a token for.
            password (str): The account password for the user you want to create a token.
            scope (str): The scope of the token being created.

        Returns:
            dict: The JSON response from the API which includes the attributes of the token
            or the error returned.
        """
        OAUTH2_TOKEN_URL = Config().get_base_url() + '/oauth2/token'
        request = post(OAUTH2_TOKEN_URL, params={
            "username": username,
            "password": password,
            "grant_type": "password",
            "scope": scope
        }, headers={
            "Authorization": "Basic " + Config().get_encoded_credentials(),
            "Accept": "application/json",
            "Content-Type": "application/x-www-form-urlencoded"
        })

        return request.body
	def init_flow(self, dpid):
		header = {'Content-type':'application/json'}
		body = {'datapathId':"{:0>16x}".format(dpid)}
		LOG.debug("body = " + str(body))
		LOG.info("Request initFlow body = " + str(body))
		res = unirest.post(CONF.ofpm_init_flow_url, headers=header, params=str(body), callback=self.__http_response__)
		return
Example #50
0
    def __init__(self, url=None):

        #print "here i am"
        if url:
            # retrieve with post method, put for create, get for read, delete for delete
            # unvisitedurls http://localhost:5000/unvisitedurls?start=0&offset=10&spider=6w
            unirest.timeout(180)
            req = unirest.post(url, headers={"Accept":"application/json"})
            self.start_urls = [data['url'] for data in req.body['data']]
            self.name = url[url.find('spider=')+7:]

            self.visitedurldict = OrderedDict()
            self.datadict       = OrderedDict()
            self.filedict       = OrderedDict()
            self.deadurldict    = OrderedDict()

            self.visitedurldict['urls'] = []
            self.datadict['datas']      = []
            self.filedict['files']      = []
            self.deadurldict['urls']    = []

            rules = (
                Rule(sle(allow=("http://book.douban.com/isbn/\d+$")), callback="parse", follow=True),
                Rule(sle(allow=("http://book.douban.com/subject/\d+$")), callback="parse", follow=True),
            )
        # def __del__(self) work
        dispatcher.connect(self.spider_closed, signals.spider_closed)
Example #51
0
File: yay.py Project: vayan/yay
 def on_pubmsg(self, serv, ev):
     canal = ev.target()
     message = ev.arguments()[0].lower()
     if self.channels[canal].has_user("Yppy"):
         return
     url = re.search("(?P<url>https?://[^\s]+)", message)
     if url:
         url = url.group(0)
         try:
             self.lasturl = url
             hostname = urlparse.urlparse(url).hostname
             g = Goose()
             article = g.extract(url=url)
             tinyurl = urllib2.urlopen("http://tinyurl.com/api-create.php?url=" + url).read()
             title = article.title.encode('utf-8')[:70]
             ret = "Title : %s (%s) | %s" % (title, hostname, tinyurl)
             serv.privmsg(canal, ret)
         except:  # todo log error
             e = sys.exc_info()[0]
             print(e)
             return
     if "!sum" in message:
         try:
             response = unirest.post("http://192.81.222.194:1142/api",{}, {"url": self.lasturl})
             print response.body
             for bullet in response.body:
                 serv.privmsg(canal, ("* %s" % (bullet).encode('utf-8')))
         except:  # todo log error
             e = sys.exc_info()[0]
             print(e)
             return
def build():
  jenkins = request.args.get('jenkins')
  jenkins = jenkins if jenkins.startswith('http://') or jenkins.startswith('https://') else 'http://%s' % jenkins
  jenkins = jenkins[:-1] if jenkins.endswith('/') else jenkins
  job = request.args.get('job')
  token = request.args.get('token', None)
  dockerfiles = request.args.get('dockerfiles', None)
  query = '' if token is None else 'token=%s' % token
  
  if dockerfiles is not None:
    query += '&dockerfiles=' + dockerfiles

  json = request.json

  if 'push' in json:
    params = {'git_hash': json['push']['changes'][0]['new']['target']['hash']}
  else:
    params = {
      'git_hash': json['changesets']['values'][0]['toCommit']['displayId'],
      'slug': json['repository']['slug'],
      'project_key': json['repository']['project']['key']
    }

  # forward the request
  jenkins_url = '%s/job/%s/buildWithParameters?%s' % (jenkins, job, query)
  response = post(jenkins_url, params = params)

  if (response.code in range(400, 500)):
    return "Request error"
  elif (response.code >= 500):
    return "Server error"
  else:
    return make_response(response.raw_body, response.code, {})
Example #53
0
 def test_post(self):
     response = unirest.post("http://httpbin.org/post", params={"name": "Mark", "nick": "thefosk"})
     self.assertEqual(response.code, 200)
     self.assertEqual(len(response.body["args"]), 0)
     self.assertEqual(len(response.body["form"]), 2)
     self.assertEqual(response.body["form"]["name"], "Mark")
     self.assertEqual(response.body["form"]["nick"], "thefosk")
Example #54
0
def create_skyscan_session():
    """
	Using unirest and the skyscanner api to get live ticket quotes directly from flight agencies.
	A successful response contains no content. The session key to poll the results are provided in the Location header of the response. The last value of the location header contains the session key which is required when polling the session
	"""
    response = unirest.post(
        "https://skyscanner-skyscanner-flight-search-v1.p.rapidapi.com/apiservices/pricing/v1.0",
        headers={
            "X-RapidAPI-Host": "skyscanner-skyscanner-flight-search-v1.p.rapidapi.com",
            "X-RapidAPI-Key": "SIGN-UP-FOR-KEY",
            "Content-Type": "application/x-www-form-urlencoded",
        },
        params={
            "inboundDate": "2019-09-10",
            "cabinClass": "business",
            "children": 0,
            "infants": 0,
            "country": "US",
            "currency": "USD",
            "locale": "en-US",
            "originPlace": "SFO-sky",
            "destinationPlace": "LHR-sky",
            "outboundDate": "2019-09-01",
            "adults": 1,
        },
    )
Example #55
0
def index():
    #they are submitting the form, so post and redirect
    if request.args.get('q1') is not None:
        #post the data
        #TODO: validate that this is an actual family
        data = {}
        data['family'] = request.args.get('family')
        data['guide_review'] = request.args.get('q1')
        data['wanting'] = request.args.get('q2')
        data['extraneous'] = request.args.get('q3')
        response = unirest.post(os.environ['CLERK_URL'] + 'followup/', headers=HEADERS,
                                params = json.dumps(data))
        print response.body
        #redirect
        return render_template('submitted.html')

    #they are asking for a new form
    famID = request.args.get('id')
    if famID is None:
        return render_template('index.html')
    else:
        fam = get(famID)
        try:
            name = fam['name']
        except TypeError:
            return "invalid ID in URL"
        else:
            data = {'name': name, 'id':famID}
            return render_template('followup.html', data=data)
def push_daily_app_loads_device(device_list):
	response = unirest.post(
	#	"https://push.geckoboard.com/v1/send/106305-6557c1f1-9c30-4701-8940-971fc1b7eb3c",
		"https://push.geckoboard.com/v1/send/106305-58cd87cd-15ac-409a-a379-f7097abc1e9d",
		headers={"Accept": "application/json", "Content-Type": "application/json"},
		params=json.dumps({
		  "api_key": geckoboard_key,
		  "data": {
	#"type": "reverse",
	"percentage": "hide",
	"item": [
	{
	"value": device_list[1][0], #apploads device one 
	"label": device_list[0][0] #device one name
	},
	{
	"value": device_list[1][1], #apploads device two
	"label": device_list[0][1] #device two name
	},
	{
	"value": device_list[1][2], #apploads device three
	"label": device_list[0][2] #device three name
	},
	{
	"value": device_list[1][3], #apploads device four
	"label": device_list[0][3] #device four name
	},
	{
	"value": device_list[1][4], #apploads device five
	"label": device_list[0][4] #device five name
	}                                                      
	]
	}}))
Example #57
0
def mutual_fund_live_price(scheme_code):
	
	mutual_fund_price = ""
	
	params = ("{\"scodes\":[" + str(scheme_code)  + "]}")

	# mashape api for fetching mutual fund prices
	# https://market.mashape.com/nviror/mutual-funds-nav-india
	response = unirest.post("https://mutualfundsnav.p.mashape.com/",
		headers={
				"X-Mashape-Key": settings.MASHAPE_API_KEY,
				"Content-Type": "application/json",
				"Accept": "application/json"
				},
			params=params
		)
	
	# sample response for the mashape api response.body = [{u'date': u'2017-01-16', u'nav': u'10.9033', u'scode': 138220}]		
	
	if type(response.body) is list:
		mutual_fund_price = response.body[0]['nav']
	else:
		mutual_fund_price = 'N/A'

	return mutual_fund_price