Python - 尝试将文件保存到 Docker 卷中

Python - Trying to Save File into Docker Volume

我正在尝试在 Docker 容器中的 json 中写入一个 python 文件。我在容器中使用 Jupyter Notebook 从 NBA API 加载一些 url,最终我想将它写入某处的 NoSql 数据库,但现在我希望将文件保存在 Docker 容器.. 不幸的是,当我 运行 这个 Python 代码时,我得到了错误

FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/nba-matches/0022101210.json'

这是 Python 代码...我是 运行ning

from run import *
save_nba_matches(['0022101210'])

在 Jupyter 笔记本上。

Python脚本:

import os
import urllib.request
import json
import logging

BASE_URL = 'https://cdn.nba.com/static/json/liveData/playbyplay/playbyplay_'
PATH = os.path.join(os.getcwd(), 'nba-matches')
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)


def save_nba_matches(match_ids):
    for match_id in match_ids:
        match_url = BASE_URL + match_id + '.json'
        json_file = os.path.join(PATH, match_id+'.json')

        web_url = urllib.request.urlopen(
            match_url)
        data = web_url.read()
        encoding = web_url.info().get_content_charset('utf-8')
        json_object = json.loads(data.decode(encoding))
        with open(json_file, "w+") as f:
            json.dump(json_object, f)
        logging.info(
            'JSON dumped into path: [' + json_file + ']')

Dockerfile:

FROM python:3

WORKDIR /usr/src/app

COPY requirements.txt ./

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["jupyter", "notebook", "--port=8888", "--no-browser", "--ip=0.0.0.0", "--allow-root"]

最后,docker-compose.yml

version: '3.4'
services:
  sports-app:
    build: .
    volumes:
      - '.:/usr/src/app'
    ports:
      - 8888:8888

根据错误,您没有名为“nba-matches”的目录,而函数 save_nba_matches 需要它;您可以添加目录验证,例如

os.makedirs(PATH, exist_ok=True)

run.py

import os
import urllib.request
import json
import logging

BASE_URL = 'https://cdn.nba.com/static/json/liveData/playbyplay/playbyplay_'
PATH = os.path.join(os.getcwd(), 'nba-matches')
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)


def save_nba_matches(match_ids):
    for match_id in match_ids:
        match_url = BASE_URL + match_id + '.json'
        json_file = os.path.join(PATH, match_id+'.json')
        web_url = urllib.request.urlopen(
            match_url)
        data = web_url.read()
        encoding = web_url.info().get_content_charset('utf-8')
        json_object = json.loads(data.decode(encoding))
        os.makedirs(PATH, exist_ok=True)
        with open(json_file, "w+") as f:
            json.dump(json_object, f)
        logging.info(
            'JSON dumped into path: [' + json_file + ']')

或者只是手动创建目录 nba-matches 它会起作用