【问题标题】:JSONDecodeError when trying to make request counter with Django尝试使用 Django 创建请求计数器时出现 JSONDecodeError
【发布时间】:2021-08-21 15:47:58
【问题描述】:

所以我想在我的 django 项目中使用 JSON 文件创建一个“reqcount”的东西,但是当我运行它时,我得到了这个错误:

Environment:


Request Method: GET
Request URL: http://localhost:8000/testing/reqcount/

Django Version: 3.2.6
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'testing']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\chris\Desktop\WEBSITE\testing\views.py", line 17, in req_count
    return HttpResponse(json.load(f))
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 293, in load
    return loads(fp.read(),
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

Exception Type: JSONDecodeError at /testing/reqcount/
Exception Value: Expecting value: line 1 column 1 (char 0)

这是我的views.py代码(忽略“hello”函数):

from django.shortcuts import render
from django.http import HttpResponse
import json

def hello(request):
    return HttpResponse('Hello, World!')


def req_count(request):
    # TODO: Update the amount of requests the "reqcount" url has gotten, then return it
    with open('..\\data.json', 'w+') as f:
        data = json.load(f)
        data['views']['reqcount']['reqs'] += 1
        json.dump(data)

        return HttpResponse(data['views']['reqcount']['reqs'])

注意事项:

  • 我使用的是 Windows 10
  • 我使用的是 Python 3.8
  • 我正在使用 pipenv 2021.5.29
  • 我使用的是 Django 3.2.6
  • 通过运行“py manage.py runserver”启动 Web 服务器时,我没有收到任何错误

编辑: 我将代码更改为:

from django.shortcuts import render
from django.http import HttpResponse
import json

def hello(request):
    return HttpResponse('Hello, World!')

def req_count(request):
    with open('data.json', "a+") as f:
        data = json.loads(f.read())

    with open('data.json', "w+") as f:
        data['views']['reqcount']['reqs'] += 1
        f.write(json.dumps(data))

    return HttpResponse(data['views']['reqcount']['reqs'])

我的错误改为:

Environment:


Request Method: GET
Request URL: http://localhost:8000/testing/reqcount/

Django Version: 3.2.6
Python Version: 3.8.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'testing']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\chris\Desktop\WEBSITE\testing\views.py", line 10, in req_count
    data = json.loads(f.read())
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

Exception Type: JSONDecodeError at /testing/reqcount/
Exception Value: Expecting value: line 1 column 1 (char 0)

【问题讨论】:

  • 根据给定的回溯,错误是由return HttpResponse(json.load(f)) 语句触发的,并且在给定的错误sn-p中找不到
  • 对于 Windows 上的那种文件路径名,您将需要一个原始字符串。此外,您的代码中没有任何内容表明“w+”是打开文件的合适模式,因为您只能从中读取文件
  • @DarkKnight 呢json.dump(data)

标签: python json django exception json-deserialization


【解决方案1】:

由于信誉点低(低于 50),我无法发表评论以询问更多信息

我认为问题在于,如果您的 JSON 文件为空并尝试读取,您将获得 JSONDecodeError,但如果文件中有有效的 JSON 数据则不会。使用w+,即使文件具有有效的 JSON 数据,您也会收到相同的错误,因为它会在执行任何操作之前清除文件(或更确切地说是覆盖文件)内容。

我能想到的解决方案是创建两个函数来读取和更新reqs 属性。

假设 JSON 文件不为空,您可能会有这样的情况:

file.json

{
    "views": {
        "reqcount": {
            "reqs": 1    
        }
    }
}
def read_json_file(filename):
    """
    read data from json file 
    return: dict
    """
    with open(filename, "a+") as file:  # use a+ to deal with the case where the file does not exist
        data = json.load(file)
        return data


def update_json_file(filename, data):
    """ update the json file by changing the 'reqs` count """
    with open(filename, "w+") as file:
        data['views']['reqcount']['reqs'] += 1
        file.write(json.dumps(data))
        return data

然后你可以在视图中调用这些函数例如

def req_count(request):
    # TODO: Update the amount of requests the "reqcount" url has gotten, then return it
    data = read_json_file("file.json")
    updated_data = update_json_file("file.json", data)

    return HttpResponse(updated_data['views']['reqcount']['reqs'])

所以每次调用视图时,计数都会更新。

【讨论】:

  • JSON 文件不为空。我也无法访问我的电脑,所以给我大约 12 小时,如果它有效,我会接受你的回答
  • 测试视图后JSON文件也完全不变
  • 这个答案不起作用。我确实发现“..\\data.json”是问题的一部分。我用运行print(f.read()) 时工作的“json.data”替换了所有这些路径,但问题仍未解决
猜你喜欢
  • 2021-12-26
  • 2020-11-30
  • 2014-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 2013-03-04
  • 2020-12-07
  • 2019-06-03
相关资源
最近更新 更多