Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/url/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python GCS生成\u签名\u Url在加载时过期_Python_Url_Google Cloud Platform_Google Cloud Storage - Fatal编程技术网

Python GCS生成\u签名\u Url在加载时过期

Python GCS生成\u签名\u Url在加载时过期,python,url,google-cloud-platform,google-cloud-storage,Python,Url,Google Cloud Platform,Google Cloud Storage,我正在实现一些代码来为json文件中指定的一些图像生成签名url,这是用于生成它们的方法 def geturl(image_name): storage_client = storage.Client() bucket = 'Bucket Name' source_bucket = storage_client.get_bucket(bucket) blobs = source_bucket.list_blobs() for blob in blobs:

我正在实现一些代码来为json文件中指定的一些图像生成签名url,这是用于生成它们的方法

def geturl(image_name):
    storage_client = storage.Client()
    bucket = 'Bucket Name'
    source_bucket = storage_client.get_bucket(bucket)
    blobs = source_bucket.list_blobs()
    for blob in blobs:
        if image_name == blob.name:
            url_lifetime = 3600
            serving_url = blob.generate_signed_url(url_lifetime)
            return serving_url
    return 
在此之后,它们被用于img scr,但是当加载页面时,图像不会加载,并且在url之后,我收到错误消息

提供的令牌已过期 请求签名截止时间:1970-01-01T10:00:00+00:00


即使在更改生存期时,错误消息仍然存在

您的参数
url\u生存期
未正确初始化。正确的含义是
过期日期
,它是从1970年1月1日格林威治标准时间起以秒为单位的值。您的过期时间为1970年1小时

正确的方法是
当前时间+3600

有很多方法可以获取当前时间。示例:
int(time.time())
,它以秒为单位返回时区中的当前时间。通常,您需要将当前时间转换为GMT,然后获取秒数

注意:在这个答案中,我使用的GMT与UTC的用法相同

from datetime import timezone, datetime
int(datetime.now(tz=timezone.utc).timestamp()

让我再举两个例子:

一,

定义符号gcp blob url(动词、对象路径、内容类型、过期):

ServiceAccountCredentials.from_json_keyfile_name(settings.GOOGLE_APPLICATION_CRE 牙科)

例2

from oauth2client.service_account import ServiceAccountCredentials

import base64

from six.moves.urllib.parse import urlencode, quote

GCS_API_ENDPOINT = 'https://storage.googleapis.com'

expiration_in_epoch = int(expiration.timestamp())

signature_string = ('{verb}\n'

                '{content_md5}\n'

                '{content_type}\n'

                '{expiration}\n'

                '{resource}')

signature = signature_string.format(verb=verb,

    content_md5='',

    content_type='',

    expiration=expiration_in_epoch,

    resource=obj_path)

creds = 
signature = creds.sign_blob(signature)[1]

encoded_signature = base64.b64encode(signature)

base_url= GCS_API_ENDPOINT + obj_path

storage_account_id = creds.service_account_email

return '{base_url}?GoogleAccessId={account_id}&Expires={expiration}&Signature={signature}'.format(base_url=base_url,
    account_id=storage_account_id,
    expiration = expiration_in_epoch,
    signature=quote(encoded_signature))