Esempio n. 1
0
def getWeather(sentence):

    api_key = api
    location = nounExtraction3(sentence)
    base_url = "http://api.openweathermap.org/data/2.5/weather?"
    if (len(location) == 0):
        city_name = getLocation()
        complete_url = base_url + "appid=" + api_key + "&q=" + city_name
        response = requests.get(complete_url)
        x = response.json()
        if x["cod"] != "404":
            z = x["weather"]
            weather_description = z[0]["description"]
            text = "The current weather is " + weather_description
            speak(text)
        else:
            speak("Not found")
    else:
        location = list(location)
        city_name = location[0]
        complete_url = base_url + "appid=" + api_key + "&q=" + city_name
        response = requests.get(complete_url)
        x = response.json()
        if x["cod"] != "404":
            z = x["weather"]
            weather_description = z[0]["description"]
            text = "The current weather is " + weather_description
            print(text)
            speak(text)
        else:
            speak("Not found")
Esempio n. 2
0
def get_space(space_key, offset):
    path = 'space/' + space_key + '/content'
    query = {'limit': 50, 'start': offset}
    response = requests.get(jira_url + path, params=query, headers=headers)
    j_data = response.json()
    #print(decode(json.dumps(j_data, sort_keys=True, ensure_ascii=True, indent=4, separators=(",", ": ")),'unicode-escape'))
    return j_data['page']['results']
Esempio n. 3
0
def post_register_user_image(idaccounts, userdata, url, callback):

    identifier = userdata['userdata']['identifier']

    file_name = identifier + ".jpg"
    file_path = "../res/" + file_name

    urllib.request.urlretrieve(url, file_path)

    file = open(file_path, "rb")

    request_url = top_level_url + "api/userprofilepictureuploadprelogin"

    files = {'file': file}

    params = {'idaccounts': idaccounts, 'identifier': identifier}

    try:
        response = requests.post(request_url,
                                 files=files,
                                 auth=(userdata['email'],
                                       userdata['password']),
                                 data=params)
    except requests.exceptions.RequestException as e:
        print('post_jsondata HTTPError code: ', e)
        return False
    else:
        print(response.json())
        callback(idaccounts)
Esempio n. 4
0
def hf_api_runner(method, path, data=None):
    api_token, workspace_id = get_auth_info()
    response = requests.request(
        method,
        f"{HACKERFORMS_API_URL}/workspaces/{workspace_id}/{path}",
        data=json.dumps(data) if data else None,
        headers={"content-type": "application/json", "API-Authorization": api_token},
    )
    return response.json()
Esempio n. 5
0
def hf_hasura_runner(query, variables={}):
    api_token = get_credentials()
    response = requests.post(
        HACKERFORMS_HASURA_URL,
        data=json.dumps({"query": query, "variables": variables}),
        headers={"content-type": "application/json", "API-Authorization": api_token},
    )
    jsond = response.json()
    # print(jsond)
    return jsond["data"]
Esempio n. 6
0
def send_response(body):
    print("Request Body", body, file=sys.stdout, flush=True)
    url = INSTANCE_URL + "/" + PRODUCT_ID + "/" + PHONE_ID + "/sendMessage"
    headers = {
        "Content-Type": "application/json",
        "x-maytapi-key": API_TOKEN,
    }
    response = requests.post(url, json=body, headers=headers)
    print("Response", response.json(), file=sys.stdout, flush=True)
    return
Esempio n. 7
0
def swift_cloud_status(request):
    try:
        keystone = Keystone(request)
    except Exception as err:
        log.exception(f"Keystone error: {err}")
        return render(request, "vault/swift_cloud/status.html", {
            "projects": [],
            "error": "Keystone Error"
        })

    environ = settings.ENVIRON
    if not environ and "localhost" in request.get_host():
        environ = "local"

    user = request.user
    group_ids = [g.id for g in user.groups.all()]
    projects = []
    keystone_projects = keystone.project_list()

    try:
        group_projects = GroupProjects.objects.filter(group_id__in=group_ids,
                                                      owner=True)
        for project in keystone_projects:
            for gp in group_projects:
                if project.id == gp.project:
                    projects.append({
                        "id": project.id,
                        "name": project.name,
                        "description": project.description,
                        "environment": environ,
                        "team": gp.group.name,
                        "status": "",
                        "metadata": {}
                    })
        projects.sort(key=lambda p: p["name"].lower())
    except Exception as err:
        log.exception(f"Keystone error: {err}")

    # Get transfer status for all projects in swift cloud tools api
    sct_client = SCTClient(settings.SWIFT_CLOUD_TOOLS_URL,
                           settings.SWIFT_CLOUD_TOOLS_API_KEY)
    data = []
    try:
        response = sct_client.transfer_status_by_projects(
            [p["id"] for p in projects])
        if response.ok:
            data = response.json()
    except Exception as err:
        log.exception(f"Swift Cloud Tools Error: {err}")

    return render(request, "vault/swift_cloud/status.html", {
        "projects": json.dumps(projects),
        "migration_data": json.dumps(data)
    })
Esempio n. 8
0
def getTemprature(sentence):

    api_key = api
    base_url = "http://api.openweathermap.org/data/2.5/weather?"

    location = nounExtraction3(sentence)

    if (len(location) == 0):
        city_name = getLocation()
        complete_url = base_url + "appid=" + api_key + "&q=" + city_name
        response = requests.get(complete_url)
        x = response.json()
        if x["cod"] != "404":
            y = x["main"]
            current_temperature = y["temp"] - 273.15
            current_temperature = round(current_temperature, 2)

            text = "The temperature is " + str(
                current_temperature) + " " + "Degree Celsius "
            print(text)
            speak(text)
        else:
            speak("Not found")

    else:
        location = list(location)
        city_name = location[0]
        complete_url = base_url + "appid=" + api_key + "&q=" + city_name
        response = requests.get(complete_url)
        x = response.json()
        if x["cod"] != "404":
            y = x["main"]
            current_temperature = y["temp"] - 273.15
            current_temperature = round(current_temperature, 2)
            text = "The temperature is " + str(
                current_temperature) + " " + "Degree Celsius "
            print(text)
            speak(text)
        else:
            speak("Not found")
Esempio n. 9
0
def get_page(page_id):
    '''Get page by id [page_id]
    '''
    path = 'content/' + page_id
    query = {'expand': 'body.view'}
    response = requests.get(jira_url + path, params=query, headers=headers)
    j_data = response.json()
    print(
        json.dumps(j_data,
                   sort_keys=True,
                   ensure_ascii=True,
                   indent=4,
                   separators=(",", ": ")))
    return j_data['body']['view']['value']
Esempio n. 10
0
def setup_webhook():
    if PRODUCT_ID == "" or PHONE_ID == "" or API_TOKEN == "":
        print(
            "You need to change PRODUCT_ID, PHONE_ID and API_TOKEN values in app.py file.",
            file=sys.stdout,
            flush=True)
        return
    public_url = ngrok.connect(9000)
    url = INSTANCE_URL + "/" + PRODUCT_ID + "/setWebhook"
    print("url", url, file=sys.stdout, flush=True)
    headers = {
        "Content-Type": "application/json",
        "x-maytapi-key": API_TOKEN,
    }
    body = {"webhook": public_url.public_url + "/webhook"}
    response = requests.post(url, json=body, headers=headers)
    print("webhook ", response.json())
Esempio n. 11
0
 def do_json(self, command, data=None, params=None, include_engine=True):
     """Issue a command to the server, parse & return decoded JSON."""
     if params is None:
         params = {}
     params['project'] = self.project_id
     if include_engine:
         if data is None:
             data = {}
         data['engine'] = self.engine.as_json()
     if command == 'delete-project':
         response = self.server.urlopen(command, params=params)
         response = response.json()
     else:
         response = self.server.urlopen_json(command, params=params, data=data)
     if 'historyEntry' in response:
         # **response['historyEntry'] won't work as keys are unicode :-/
         he = response['historyEntry']
         self.history_entry = history.HistoryEntry(he['id'], he['time'],
                                                   he['description'])
     return response
Esempio n. 12
0
def swift_cloud_price_preview(request):
    amount = request.GET.get('amount')

    if not amount:
        return JsonResponse({"error": "Missing amount parameter"}, status=400)

    sct_client = SCTClient(settings.SWIFT_CLOUD_TOOLS_URL,
                           settings.SWIFT_CLOUD_TOOLS_API_KEY)

    response = sct_client.billing_get_price_from_service(
        settings.SWIFT_CLOUD_GCP_SERVICE_ID, settings.SWIFT_CLOUD_GCP_SKU,
        int(amount))

    result = {"price": None, "currency": None}
    status = 500

    if response.ok:
        result = response.json()
        status = 200

    return JsonResponse(result, status=status)
Esempio n. 13
0
 def resolve(self):
     winner_chain = self.chain
     replace = False
     for node in self.__peer.nodes:
         url = 'http://{}/chain'.format(node)
         try:
             response = requests.get(url)
             node_chain = response.json()
             node_chain = [
                 Block(
                     block['index'],
                     block['previous_hash'],
                     # nested list => block['transactions']
                     [
                         Transaction(tx['sender'], tx['recipient'],
                                     tx['signature'], tx['amount'])
                         for tx in block['transactions']
                     ],
                     block['proof'],
                     block['timextamp']) for block in node_chain
             ]
             node_chain_length = len(node_chain)
             local_chain_length = len(winner_chain)
             if node_chain_length > local_chain_length and Verification.verify_chain(
                     node_chain):
                 # longest valid chain wins
                 winner_chain = node_chain
                 replace = True
         except requests.ConnectionError:
             continue
     self.resolve_conflicts = False
     self.chain = winner_chain
     if replace:
         self.__open_transactions = []
     self.save_data()
     return replace
Esempio n. 14
0
def get_sg_rules(token):
    url = "https://dc1-adm1.demo.netapp.com/api/v3/grid/alert-rules"
    myheaders = {"Authorization": "Bearer " + token['data']}
    response = requests.get(url, headers=myheaders, verify=False)
    checks = response.json()
    return (checks)
Esempio n. 15
0
def get_data(url):
    response = requests.get(url)    
    try:
        return response.json()
    except ConnectionError as e:
        return e
Esempio n. 16
0
            'grant_type':
            'password',
            'username':
            '******',
            'password':
            '******',
            'scope':
            'openid profile email',
            'audience':
            'https://welcome/',
            'client_id':
            'PdkS09Ig0EYVGK9KPYwncjKMGzXnAasI',
            'client_secret':
            '--OuOrb1541ddztN17yBA_yMuy_Ekrc-NikGijgqgtMd9kRvAI6dmMkpvqXOGuSX'
        })
    return r.json()['access_token']


token = get_access_token()
#token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6InBvV3dCYWRCMjIyejlBY3N2SHEwMiJ9.eyJpc3MiOiJodHRwczovL3N1cm9lZ2luNTAzLmV1LmF1dGgwLmNvbS8iLCJzdWIiOiJhdXRoMHw2MDkyOWQyMjU1YzQ1ZjAwNjgxZWM0ZDEiLCJhdWQiOiJodHRwczovL3dlbGNvbWUvIiwiaWF0IjoxNjIyMjQyMjEwLCJleHAiOjE2MjIyNDk0MTAsImF6cCI6IlBka1MwOUlnMEVZVkdLOUtQWXduY2pLTUd6WG5BYXNJIiwic2NvcGUiOiIifQ.GqsBHjixW5dh-f12F9IAGrzkaVUvd_hYPFlYI5TTT7HveOUwdcVmAIRlkUEhvFnPGFcmySohM_i31ykixr0eGnOpM7RE4Sv3yfhnMwFvTVWszEA-x2c0O9KeC130y2vC4Zg8LzqT8db_StDS8dDcRKhJk0ndkVWT3PK8P9p_35HyHnc8GtfmVLdIuzWrJ-ZW6dsZLAgr3Us6IU0kPb7A5qHgH33l7XjbtcAQsyyLTcskszzW_xpOy9v_Re9DRTs_AzIlwXvrerDRSG0PWApuJ0-MInh2W1l11RnhUtbF7gwITCjcuwWoZxh8qRjgdZ3JArSR_m7eFO9ka_DExknkXg'
auth_headers = {'Authorization': f'Bearer {token}'}
# response = requests.post("https://secure-gorge-99048.herokuapp.com/api/application/create/", headers=auth_headers)
print(auth_headers)
response = requests.get(
    "https://secure-gorge-99048.herokuapp.com/api/application/last/",
    headers=auth_headers)
print(response.json())
if type(response.json()['status']):
    print('YEs')
print(response.json()['status'])
Esempio n. 17
0
 def urlopen_json(self, command, *args, **kwargs):
     """Open a Refine URL, optionally POST data, and return parsed JSON."""
     response = self.urlopen(command, *args, **kwargs)
     response = response.json()
     self.check_response_ok(response)
     return response
Esempio n. 18
0
#Passing second filter for only open offenses.
open = "OPEN"

#qRadar URL with all the flters passed/
url = "https://qRadarURL/api/siem/offenses?filter=status%20%3D%20%22{open}%22%20and%20start_time%20%3E%20{etime}".format(open=open, etime=epochtime)

#querystring = {"status": "OPEN"}

headers = {
    'Accept': "application/json",
    'SEC': security_token,
    'cache-control': "no-cache",
}
response = requests.request("GET", url, headers=headers, verify=False)

data = response.json()

http = urllib3.PoolManager()

if data == []:
    logger.info("No Data")
else:
    logger.info('Number of offenses retrived: ' + str(len(data)))
    for rows in data:
        logger.info('\n')
        logger.info("*****")
        logger.info('Offense ID: ' + str(rows['id']))
        logger.info('Description: ' + str(rows['description']))
        logger.info('Rules -  ID: ' + str(rows['rules'][0]['id']))
        logger.info('Rules -  Type: ' + str(rows['rules'][0]['type']))
        logger.info('Categories Listed: ' + str(rows['categories'][0]))
Esempio n. 19
0
def swift_cloud_project_status(request):
    project_id = request.GET.get('project_id')

    if not project_id:
        raise Http404

    try:
        keystone = Keystone(request)
        project = keystone.project_get(project_id)
    except Exception as err:
        log.exception(f"Keystone error: {err}")
        return render(request, "vault/swift_cloud/project_status.html", {
            "project": None,
            "error": "Keystone Error"
        })

    sct_client = SCTClient(settings.SWIFT_CLOUD_TOOLS_URL,
                           settings.SWIFT_CLOUD_TOOLS_API_KEY)
    status = ""
    data = {}

    try:
        response = sct_client.transfer_get(project_id)
        if response.ok:
            data = response.json()
        else:
            status = _("Couldn't get migration data")
    except Exception as err:
        log.exception(f"Swift Cloud Tools Error: {err}")

    if response.status_code == 404:
        status = _("Migration not initialized yet")

    if response.status_code < 300:
        status = _("Waiting in migration queue")

    if data.get("initial_date") and not data.get("final_date"):
        status = _("Migrating...")

    if data.get("final_date"):
        status = _("Migration Completed")

    http_conn, storage_url = get_conn_and_storage_url(request, project_id)
    auth_token = request.session.get('auth_token')
    head_account = {}

    try:
        head_account = client.head_account(storage_url,
                                           auth_token,
                                           http_conn=http_conn)
    except Exception as err:
        log.exception(f'Exception: {err}')

    if head_account.get("x-account-meta-cloud-remove"):
        status = _("Marked for removal")

    return render(
        request, "vault/swift_cloud/project_status.html", {
            "project": project,
            "status": status,
            "metadata": json.dumps(head_account),
            "migration_data": json.dumps(data)
        })