【发布时间】: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: