繁体   English   中英

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 代码...我正在运行

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”的目录,而 function save_nba_matches 需要它; 您可以添加目录验证,例如

os.makedirs(PATH, exist_ok=True)

运行.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 它会起作用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM