【问题标题】:Unable to import json objects from json file in DJANGO无法从 DJANGO 中的 json 文件导入 json 对象
【发布时间】:2017-02-14 08:52:19
【问题描述】:

我无法从 Django 中的 json 文件创建 json 对象。这是代码。 我有一个名为 out.json 的文件,其中包含 json 对象。我想发送这些对象作为响应。我收到一个错误提示

/projectboard/random 处的 FileNotFoundError [Errno 2] 没有这样的文件或目录:'out.json'

views.py

from django.shortcuts import render, HttpResponseRedirect
import sys, os
import json  
from django.http import JsonResponse
from tempfile import *

import subprocess


# Create your views here.
from django.http import HttpResponse

def random(request):
    os.system('python pypy.py')

    with open('out.json') as json_data:
        data = json.load(json_data)
        print(data)

    return JsonResponse(data)

urls.py

from rest_framework.routers import DefaultRouter
from django.views.generic import TemplateView
from django.conf.urls import url, include
from . import views

urlpatterns = [
      url(r'^random$', views.random, name='random'),
      url(r'^view/(?P<id_remedio>\w+)/$', views.view, name='view'),
      url(r'^view/$', views.view, name='view')
]

【问题讨论】:

  • out.json 存储在哪里?
  • out.json 存放在同一目录,即Projectboard
  • 似乎找不到 out.json 。尝试给出out.json的views.py对应的绝对路径或相对路径@
  • 将 out.json 移至此目录/projectboard/random 或获取文件的绝对路径并在此处传递with open(absolute_path) as json_data:

标签: python json django


【解决方案1】:

out.json 文件应该与 manage.py 文件在同一目录

foo/
    manage.py
    foo/
       __init__.py
       settings.py
       urls.py
       wsgi.py

    out.json

【讨论】:

    【解决方案2】:

    将 out.json 移至目录 /projectboard/out.json

    out.json必须和views.py在同一目录下,或者和调用open(file)的py文件一样。如果您使用的是 Linux 或 OS X,请导航到 /projectboard 文件夹并键入 ls 以列出要仔细检查的文件 out.json 位于正确的路径中。否则在 Windows 机器上使用 dir

    【讨论】:

      【解决方案3】:

      我会确保包含文件的完整路径。除非您的 out.json 与试图打开它的文件位于 同一文件夹,否则您将收到该错误。

      更好的是,如果您的多个应用程序在上述文件中有对象,或者只是为了清理您的项目,我会在您的应用程序中包含一个 /fixtures/ 文件夹,并将所有 .json 文件放在那里。然后,您可以轻松地检索这些文件的根目录(可以将其包含在您的 settings.py 文件中)——类似于:

      FIXTURES_ROOT = os.path.abspath(os.path.dirname(__file__)) + '/fixtures/'
      

      然后你就可以使用

      from django.conf import settings
      ...
      json_path = settings.FIXTURES_ROOT + <YOUR_JSON_FILENAME>
      

      整个项目

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-04
        • 2020-08-21
        • 1970-01-01
        • 2017-03-25
        • 1970-01-01
        • 2014-05-17
        • 2021-09-24
        • 1970-01-01
        相关资源
        最近更新 更多