Skip to main content
 首页 » 编程设计

python之在 Python App Engine API 中写入和读取 blobstore 文件以存储时间戳

2025年05月04日21lhb25

我正在使用适用于 Google App Engine 的 python API,我想做的是从服务器加载一个文件列表,如果它已经超过一个时间间隔(例如 1 小时)。

为此我尝试将执行的最后一个运行时间存储到一个文件中,下次读取它以了解与下一个请求的当前执行时间的差异,但后来我发现GAE不允许将文件写入磁盘,所以我不得不使用 blobstore。我试图将我已经拥有的相同功能放在一起,但使用了 blobstore 功能,但即使创建了文件,每次我尝试读取它时,我都会收到一条错误消息:

FinalizationError: ApplicationError: 101 Blobkey not found. 

我不确定我在做什么是错的。我是 GAE 的新手,不知道这是否是完成我需要做的事情的最佳方法,而且我在 GAE 的文档中找不到在同一脚本中读写文件的示例文件 API。

提前感谢您给我的任何提示。

这是我的代码的摘要版本,get 和 set 函数与代码中的一样:

# imports... 
from datetime import datetime as time 
from google.appengine.api import files 
 
# create file 
last_request_file = files.blobstore.create() 
 
 
def update_list(time_interval): 
    # Get the time of the current request 
    current_time = time.now() 
 
    # Calculate timelapse between this an the last request 
    last_request = get_last_request_time(last_request_file) 
    elapsed_time = current_time - last_request 
 
    # If more than an interval update proxy list 
    if elapsed_time.total_seconds() >= time_interval: 
        # Request new list from the server 
        my_list = getList() 
 
    # Update last_request time 
    set_last_request(last_request_file) 
 
    return my_ist 
 
 
def get_last_request_time(file_name): 
    request_time = None 
 
    with files.open(file_name, 'r') as f: 
        text_time = f.read() 
        if text_time: 
            request_time = time.strptime(text_time, '%Y-%m-%d %H:%M:%S') 
        else: # file was empty 
            request_time = time.min 
 
    # Finalize to close the file. 
    files.finalize(file_name) 
 
    return request_time 
 
 
def set_last_request_time(file_name): 
    current_time = time.now() 
 
    # Open the file and write to it 
    with files.open(file_name, 'a') as f: 
        f.write(time.strftime(current_time, '%Y-%m-%d %H:%M:%S')+'\n') 
 
    # Finalize to close the file. 
    files.finalize(file_name) 

请您参考如下方法:

第一:为什么不将信息存储在任务队列中。您可以每小时运行一个任务队列来完成您的工作(获取列表)。

第二:只有在创建文件并写入文件时才使用 finalize。但是你不能在文件完成后写入文件。要更新 blobstore 中的文件,您始终必须创建一个新文件。当您读取一个文件时,您不必完成它。要读取文件,您必须使用 blobreader。请参阅:https://developers.google.com/appengine/docs/python/blobstore/blobreaderclass