【问题标题】:DJANGO: This backend doesn't support absolute pathsDJANGO:这个后端不支持绝对路径
【发布时间】:2021-03-04 05:04:24
【问题描述】:

我正在尝试为必须使用 python open() 方法打开的一些 json 文件设置路径。阅读文档我注意到必须覆盖 django.core.files.storage 中类 Storage 的路径方法,但我不知道如何覆盖它,因为我不知道如何存储此路径。

我的文件是这样的

App
--index_backend
----json
-------some_json.json
----index.py
--views.py
manage.py

我是 Django 的新手,所以如果您需要查看更多代码,请告诉我尽可能多地上传。

更新 我想要实现的是在单击按钮时调用一个函数,该按钮向http://127.0.0.1:8000/App/getValues 发送一个请求,以便运行一个调用index.py 中另一个python 函数的python 函数。 index.py 里面的 some_json.json 是打开的,但是在运行 getValues 时,它会在 /App/getValues/ 处引发 FileNotFoundError,因为它在 /App/getValues/ 中寻找 some_json.json 而不是 /App/index_backend/json/

【问题讨论】:

  • 您需要添加最少的代码。

标签: python-3.x django web django-models django-views


【解决方案1】:

在您的 index.py 文件中:

import json
import os

this_file = os.path.realpath(__file__)
this_folder = os.path.dirname(this_file)
path_to_json = os.path.join(this_folder, 'json', 'some_json.json')

with open(path_to_json) as f:
    data = json.load(f)

print(data)

【讨论】:

    【解决方案2】:

    如果您使用的是 Django 3.1+,这是一个可以在 index 中使用的方法

    from django.conf import settings
    
    BASE_DIR = settings.BASE_DIR
    
    JSON_FILE = BASE_DIR / 'App/index_backend/json/some_json.json'
    

    【讨论】:

      【解决方案3】:

      以上都不起作用,经过大量搜索,这对我有用。

      首先,添加 MEDIA ROOT 因为我需要这些 JSON 文件是动态的

      MEDIA_ROOT  = os.path.join(BASE_DIR, 'App/media')
      MEDIA_URL = '/media/'
      

      然后,在 index_backend/index.py 上导入 default_storage

      from django.core.files.storage import default_storage
      with default_storage.open('some_json.json', "r") as some_json_file:
            doSomethingJSONGLYCool(some_json_file)
      

      将媒体文件夹设置为很重要

      App
      --index_backend
      ----index.py
      --media
      ---path/to/json
      --views.py
      manage.py
      

      【讨论】:

        猜你喜欢
        • 2021-11-24
        • 2013-08-15
        • 1970-01-01
        • 2019-09-09
        • 2019-04-11
        • 2017-11-16
        • 2018-04-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多