Python googleapiclient.http() Examples

The following are code examples for showing how to use googleapiclient.http(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: eetc   Author: george-azzari   File: crud_object.py    MIT License 5 votes vote down vote up
def create_service():
    # Construct the service object for interacting with the Cloud Storage API -
    # the 'storage' service, at version 'v1'.
    # You can browse other available api services and versions here:
    #     http://g.co/dv/api-client-library/python/apis/
    return googleapiclient.discovery.build('storage', 'v1') 
Example 2
Project: eetc   Author: george-azzari   File: crud_object.py    MIT License 5 votes vote down vote up
def upload_object(bucket, filename, readers, owners):
    service = create_service()

    # This is the request body as specified:
    # http://g.co/cloud/storage/docs/json_api/v1/objects/insert#request
    body = {
        'name': filename,
    }

    # If specified, create the access control objects and add them to the
    # request body
    if readers or owners:
        body['acl'] = []

    for r in readers:
        body['acl'].append({
            'entity': 'user-%s' % r,
            'role': 'READER',
            'email': r
        })
    for o in owners:
        body['acl'].append({
            'entity': 'user-%s' % o,
            'role': 'OWNER',
            'email': o
        })

    # Now insert them into the specified bucket as a media insertion.
    # http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#insert
    with open(filename, 'rb') as f:
        req = service.objects().insert(
            bucket=bucket, body=body,
            # You can also just set media_body=filename, but for the sake of
            # demonstration, pass in the more generic file handle, which could
            # very well be a StringIO or similar.
            media_body=googleapiclient.http.MediaIoBaseUpload(
                f, 'application/octet-stream'))
        resp = req.execute()

    return resp 
Example 3
Project: eetc   Author: george-azzari   File: crud_object.py    MIT License 5 votes vote down vote up
def get_object(bucket, filename, out_file):
    service = create_service()

    # Use get_media instead of get to get the actual contents of the object.
    # http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#get_media
    req = service.objects().get_media(bucket=bucket, object=filename)

    downloader = googleapiclient.http.MediaIoBaseDownload(out_file, req)

    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print("Download {}%.".format(int(status.progress() * 100)))

    return out_file 
Example 4
Project: content   Author: demisto   File: GoogleVault.py    MIT License 5 votes vote down vote up
def connect():
    creds = get_credentials()
    try:
        service = build('vault', 'v1', http=creds.authorize(Http(disable_ssl_certificate_validation=(not USE_SSL))))
    except Exception as e:
        LOG('There was an error creating the Vault service in the \'connect\' function.')
        err_msg = 'There was an error creating the Vault service - {}'.format(str(e))
        return_error(err_msg)
    return service 
Example 5
Project: content   Author: demisto   File: GoogleVault.py    MIT License 5 votes vote down vote up
def download_storage_object(object_ID, bucket_name):
    service = connect_to_storage()
    req = service.objects().get_media(bucket=bucket_name, object=object_ID)  # pylint: disable=no-member
    out_file = io.BytesIO()
    downloader = googleapiclient.http.MediaIoBaseDownload(out_file, req)
    done = False
    while not done:
        done = downloader.next_chunk()[1]
    return out_file 
Example 6
Project: content   Author: demisto   File: GoogleVault.py    MIT License 5 votes vote down vote up
def connect_to_storage():
    try:
        creds = get_storage_credentials()
        ptth = authorized_http(creds)
        ptth.disable_ssl_certificate_validation = (not USE_SSL)
        service = build('storage', 'v1', http=ptth)
    except Exception as e:
        LOG('There was an error creating the Storage service in the \'connect_to_storage\' function.')
        err_msg = 'There was an error creating the Storage service - {}'.format(str(e))
        return_error(err_msg)
    return service 
Example 7
Project: python-docs-samples   Author: GoogleCloudPlatform   File: conftest.py    Apache License 2.0 5 votes vote down vote up
def api_client_inject_project_id():
    """Patches all googleapiclient requests to replace 'YOUR_PROJECT_ID' with
    the project ID."""
    import googleapiclient.http

    old_execute = googleapiclient.http.HttpRequest.execute

    def new_execute(self, http=None, num_retries=0):
        self.uri = self.uri.replace('YOUR_PROJECT_ID', PROJECT)
        return old_execute(self, http=http, num_retries=num_retries)

    with mock.patch(
            'googleapiclient.http.HttpRequest.execute',
            new=new_execute):
        yield 
Example 8
Project: python-docs-samples   Author: GoogleCloudPlatform   File: main.py    Apache License 2.0 5 votes vote down vote up
def upload_object(self, bucket, file_object):
        body = {
            'name': 'storage-api-client-sample-file.txt',
        }
        req = storage.objects().insert(
            bucket=bucket, body=body,
            media_body=googleapiclient.http.MediaIoBaseUpload(
                file_object, 'application/octet-stream'))
        resp = req.execute()
        return resp 
Example 9
Project: python-docs-samples   Author: GoogleCloudPlatform   File: crud_object.py    Apache License 2.0 5 votes vote down vote up
def create_service():
    # Construct the service object for interacting with the Cloud Storage API -
    # the 'storage' service, at version 'v1'.
    # You can browse other available api services and versions here:
    #     http://g.co/dv/api-client-library/python/apis/
    return googleapiclient.discovery.build('storage', 'v1') 
Example 10
Project: python-docs-samples   Author: GoogleCloudPlatform   File: crud_object.py    Apache License 2.0 5 votes vote down vote up
def upload_object(bucket, filename, readers, owners):
    service = create_service()

    # This is the request body as specified:
    # http://g.co/cloud/storage/docs/json_api/v1/objects/insert#request
    body = {
        'name': filename,
    }

    # If specified, create the access control objects and add them to the
    # request body
    if readers or owners:
        body['acl'] = []

    for r in readers:
        body['acl'].append({
            'entity': 'user-%s' % r,
            'role': 'READER',
            'email': r
        })
    for o in owners:
        body['acl'].append({
            'entity': 'user-%s' % o,
            'role': 'OWNER',
            'email': o
        })

    # Now insert them into the specified bucket as a media insertion.
    # http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#insert
    with open(filename, 'rb') as f:
        req = service.objects().insert(
            bucket=bucket, body=body,
            # You can also just set media_body=filename, but for the sake of
            # demonstration, pass in the more generic file handle, which could
            # very well be a StringIO or similar.
            media_body=googleapiclient.http.MediaIoBaseUpload(
                f, 'application/octet-stream'))
        resp = req.execute()

    return resp 
Example 11
Project: python-docs-samples   Author: GoogleCloudPlatform   File: crud_object.py    Apache License 2.0 5 votes vote down vote up
def get_object(bucket, filename, out_file):
    service = create_service()

    # Use get_media instead of get to get the actual contents of the object.
    # http://g.co/dv/resources/api-libraries/documentation/storage/v1/python/latest/storage_v1.objects.html#get_media
    req = service.objects().get_media(bucket=bucket, object=filename)

    downloader = googleapiclient.http.MediaIoBaseDownload(out_file, req)

    done = False
    while done is False:
        status, done = downloader.next_chunk()
        print("Download {}%.".format(int(status.progress() * 100)))

    return out_file 
Example 12
Project: hail   Author: hail-is   File: driver.py    MIT License 5 votes vote down vote up
def __init__(self, credentials):
        # Google API Python clients are not thread safe, create Http object per request
        # https://github.com/googleapis/google-api-python-client/blob/master/docs/thread_safety.md
        def build_request(http, *args, **kwargs):  # pylint: disable=unused-argument
            import google_auth_httplib2
            new_http = google_auth_httplib2.AuthorizedHttp(credentials=credentials)
            return googleapiclient.http.HttpRequest(new_http, *args, **kwargs)

        self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=40)

        # https://googleapis.dev/python/storage/latest/index.html
        self.storage_client = google.cloud.storage.Client(credentials=credentials)

        self.iam_client = googleapiclient.discovery.build('iam', 'v1', cache_discovery=False, credentials=credentials, requestBuilder=build_request) 
Example 13
Project: MyTwitterBot   Author: rahul1205   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def recognize_wit(self, audio_data, key, show_all=False):
        """
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Wit.ai API.

        The Wit.ai API key is specified by ``key``. Unfortunately, these are not available without `signing up for an account <https://wit.ai/>`__ and creating an app. You will need to add at least one intent to the app before you can see the API key, though the actual intent settings don't matter.

        To get the API key for a Wit.ai app, go to the app's overview page, go to the section titled "Make an API request", and look for something along the lines of ``Authorization: Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX``; ``XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX`` is the API key. Wit.ai API keys are 32-character uppercase alphanumeric strings.

        The recognition language is configured in the Wit.ai app settings.

        Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the `raw API response <https://wit.ai/docs/http/20141022#get-intent-via-text-link>`__ as a JSON dictionary.

        Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
        """
        assert isinstance(audio_data, AudioData), "Data must be audio data"
        assert isinstance(key, str), "``key`` must be a string"

        wav_data = audio_data.get_wav_data(
            convert_rate=None if audio_data.sample_rate >= 8000 else 8000,  # audio samples must be at least 8 kHz
            convert_width=2  # audio samples should be 16-bit
        )
        url = "https://api.wit.ai/speech?v=20160526"
        request = Request(url, data=wav_data, headers={"Authorization": "Bearer {}".format(key), "Content-Type": "audio/wav"})
        try:
            response = urlopen(request, timeout=self.operation_timeout)
        except HTTPError as e:
            raise RequestError("recognition request failed: {}".format(e.reason))
        except URLError as e:
            raise RequestError("recognition connection failed: {}".format(e.reason))
        response_text = response.read().decode("utf-8")
        result = json.loads(response_text)

        # return results
        if show_all: return result
        if "_text" not in result or result["_text"] is None: raise UnknownValueError()
        return result["_text"] 
Example 14
Project: addon-hassiogooglebackup   Author: samccauley   File: gbcommon.py    MIT License 5 votes vote down vote up
def getDriveService(user_agent):

    with open(TOKEN) as f:
        creds = json.load(f)

    credentials = GoogleCredentials(None,creds["client_id"],creds["client_secret"],
                                          creds["refresh_token"],None,"https://accounts.google.com/o/oauth2/token",user_agent)
    http = credentials.authorize(Http())
    credentials.refresh(http)
    drive_service = build('drive', 'v3', http)

    return drive_service 
Example 15
Project: addon-hassiogooglebackup   Author: samccauley   File: gbcommon.py    MIT License 5 votes vote down vote up
def backupFile(fileName, backupDirID, drive_service, MIMETYPE, TITLE, DESCRIPTION):

    logging.info("Backing up " + fileName + " to " + backupDirID)

    logging.debug("drive_service = " + str(drive_service))
    logging.debug("MIMETYPE = " + MIMETYPE)
    logging.debug("TITLE = " + TITLE)
    logging.debug("DESCRIPTION = " + DESCRIPTION)

    shortFileName = ntpath.basename(fileName)

    media_body = googleapiclient.http.MediaFileUpload(
        fileName,
        mimetype=MIMETYPE,
        resumable=True
    )

    logging.debug("media_body: " + str(media_body))

    body = {
        'name': shortFileName,
        'title': TITLE,
        'description': DESCRIPTION,
        'parents': [backupDirID]
    }

    new_file = drive_service.files().create(
    body=body, media_body=media_body).execute()
    logging.debug(pformat(new_file)) 
Example 16
Project: MyTwitterBot   Author: rahul1205   File: __init__.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def recognize_google(self, audio_data, key=None, language="en-US", show_all=False):
        """
        Performs speech recognition on ``audio_data`` (an ``AudioData`` instance), using the Google Speech Recognition API.

        The Google Speech Recognition API key is specified by ``key``. If not specified, it uses a generic key that works out of the box. This should generally be used for personal or testing purposes only, as it **may be revoked by Google at any time**.

        To obtain your own API key, simply following the steps on the `API Keys <http://www.chromium.org/developers/how-tos/api-keys>`__ page at the Chromium Developers site. In the Google Developers Console, Google Speech Recognition is listed as "Speech API".

        The recognition language is determined by ``language``, an RFC5646 language tag like ``"en-US"`` (US English) or ``"fr-FR"`` (International French), defaulting to US English. A list of supported language tags can be found in this `StackOverflow answer <http://stackoverflow.com/a/14302134>`__.

        Returns the most likely transcription if ``show_all`` is false (the default). Otherwise, returns the raw API response as a JSON dictionary.

        Raises a ``speech_recognition.UnknownValueError`` exception if the speech is unintelligible. Raises a ``speech_recognition.RequestError`` exception if the speech recognition operation failed, if the key isn't valid, or if there is no internet connection.
        """
        assert isinstance(audio_data, AudioData), "``audio_data`` must be audio data"
        assert key is None or isinstance(key, str), "``key`` must be ``None`` or a string"
        assert isinstance(language, str), "``language`` must be a string"

        flac_data = audio_data.get_flac_data(
            convert_rate=None if audio_data.sample_rate >= 8000 else 8000,  # audio samples must be at least 8 kHz
            convert_width=2  # audio samples must be 16-bit
        )
        if key is None: key = "AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw"
        url = "http://www.google.com/speech-api/v2/recognize?{}".format(urlencode({
            "client": "chromium",
            "lang": language,
            "key": key,
        }))
        request = Request(url, data=flac_data, headers={"Content-Type": "audio/x-flac; rate={}".format(audio_data.sample_rate)})

        # obtain audio transcription results
        try:
            response = urlopen(request, timeout=self.operation_timeout)
        except HTTPError as e:
            raise RequestError("recognition request failed: {}".format(e.reason))
        except URLError as e:
            raise RequestError("recognition connection failed: {}".format(e.reason))
        response_text = response.read().decode("utf-8")

        # ignore any blank blocks
        actual_result = []
        for line in response_text.split("\n"):
            if not line: continue
            result = json.loads(line)["result"]
            if len(result) != 0:
                actual_result = result[0]
                break

        # return results
        if show_all: return actual_result
        if not isinstance(actual_result, dict) or len(actual_result.get("alternative", [])) == 0: raise UnknownValueError()

        if "confidence" in actual_result["alternative"]:
            # return alternative with highest confidence score
            best_hypothesis = max(actual_result["alternative"], key=lambda alternative: alternative["confidence"])
        else:
            # when there is no confidence available, we arbitrarily choose the first hypothesis.
            best_hypothesis = actual_result["alternative"][0]
        if "transcript" not in best_hypothesis: raise UnknownValueError()
        return best_hypothesis["transcript"]