Python 无法在生产中的 google 云 运行 上找到文件

Python are not able to find files on google cloud run in production

我从 api 中提取数据并在本地存储和转换。它在我的 windows 机器上使用 docker 在本地工作,但在云端 运行 的生产环境中不起作用。我真的不知道为什么会这样。

app.py

...

try:
    os.mkdir(os.path.join(os.getcwd(), 'tmp'))
    os.mkdir(os.path.join(os.getcwd(), 'tmp', 'cpc'))
    os.mkdir(os.path.join(os.getcwd(), 'tmp', 'cpc', 'fin'))
    os.mkdir(os.path.join(os.getcwd(), 'tmp', 'cpc', 'raw'))
    os.mkdir(os.path.join(os.getcwd(), 'tmp', 'raw'))
    os.mkdir(os.path.join(os.getcwd(), 'tmp', 'transformed'))
except:
    print ("Creation of the directory failed")

...

loader.to_json(qcdp_final, os.path.join(os.getcwd(), 'tmp', 'raw', f'{last_week_monday}.json'))

...

load.py

...

def to_json(self, data, filename):
    self.data = data
    self.filename = filename
    with open(self.filename, 'w') as outfile:
        for row in self.data:
            json.dump(row, outfile)
            outfile.write('\n')
    outfile.close()

...

堆栈跟踪

FileNotFoundError: [Errno 2] No such file or directory: '/tmp/raw/2020-09-07.json'
at to_json (load.py:44)
at download_data_from_api (extract.py:51)
at main (app.py:39)
at dispatch_request (/usr/local/lib/python3.8/site-packages/flask/app.py:1935)
at full_dispatch_request (/usr/local/lib/python3.8/site-packages/flask/app.py:1949)
at reraise (/usr/local/lib/python3.8/site-packages/flask/_compat.py:39)
at handle_user_exception (/usr/local/lib/python3.8/site-packages/flask/app.py:1820)
at full_dispatch_request (/usr/local/lib/python3.8/site-packages/flask/app.py:1951)
at wsgi_app (/usr/local/lib/python3.8/site-packages/flask/app.py:2446)

在 Linux 系统上,禁止创建像 /tmp 这样的文件夹。这是为 os 保留的。我在我的 Dockerfile 中指定了一个工作目录,就像 WORKDIR /app 一样,并在这个目录中创建了 tmp 文件夹。这样就可以了。

不保证 /tmp 目录在容器实例之间持久存在。如果您希望这些文件成为 docker 图像的一部分,您需要将它们放在其他地方。