代码之家  ›  专栏  ›  技术社区  ›  NeoVe

filenotfounderror at/stores/-将本地JSON文件加载到Django视图中

  •  1
  • NeoVe  · 技术社区  · 7 年前

    我有这个功能:

    def postcodes(request):
        data = open('stores.json').read() 
        jsonData = json.dumps(data) 
    

    这是我的目录结构:

    ├── core
    │   ├── admin.py
    │   ├── apps.py
    │   ├── forms.py
    │   ├── __init__.py
    │   ├── migrations
    │   │   ├── __init__.py
    │   ├── models.py
    │   ├── stores.json
    │   ├── templates
    │   │   └── core
    │   │       ├── github.html
    │   │       ├── home.html
    │   │       ├── oxford.html
    │   │       ├── stores.html
    │   ├── tests.py
    │   ├── urls.py
    │   └── views.py
    

    功能在我的 views.py 文件和文件 stores.json 在同一个目录中。

    这是回溯:

    Internal Server Error: /stores/
    Traceback (most recent call last):
    File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
    File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
    File "/home/kristian/.virtualenvs/rest_tails2/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "/home/kristian/tails/restful-apis-example/core/views.py", line 83, in postcodes
    data = open('stores.json').read() #opens the json file and saves the raw contents
    FileNotFoundError: [Errno 2] No such file or directory: 'stores.json'
    [25/Nov/2018 20:07:31] "GET /stores/ HTTP/1.1" 500 75613
    

    我正考虑宣布 BASE_DIR 对于静态或模板,但我不确定这种方法。

    我从未将本地JSON文件加载到Django中,所以对此有什么想法吗?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dawit Abate    7 年前

    自从 stores.json 在核心目录中,您必须使用来自基目录的绝对路径或相对路径。IE. core/stores.json . 加用 json.loads(data)