【问题标题】:crud operation without using serializers不使用序列化程序的 crud 操作
【发布时间】:2019-12-27 07:31:00
【问题描述】:

这是错误: 在第 7 行和第 9 行;

json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

这是我的代码:

import requests
BASE_URL = 'http://127.0.0.1:8000/'
ENDPOINT = 'api/'
def get_resource(id):
    resp = requests.get(f"{BASE_URL}{ENDPOINT}{id}/")
    print(resp.status_code)
    print(resp.json())
id = input("enter some id:")
get_resource(id)

【问题讨论】:

  • 检查respContent-type 响应头。应该是application/json
  • 是的,我在回复中提到了内容类型。

标签: json django rest crud


【解决方案1】:

响应返回来自该站点的大数据,其中包含标题、状态代码和其他... 您还应该转储此响应的内容。 Read there

尝试下一个:

resp.text.json()

或者:

resp.content.json()

content 让您可以访问响应负载的原始字节,您通常希望使用 UTF-8 等字符编码将它们转换为字符串

【讨论】:

    【解决方案2】:

    这是我的观点.py:

    from django.shortcuts import render
    from django.views.generic import View
    from withoutrest.models import employee
    from django.http import HttpResponse
    import json
    from django.core.serializers import serialize
    
    
    class EmployeeDetails(View):
        def get(self, request, id, *args, **kwargs):
            emp = employee.objects.get(id=id)
            json_data = serialize('json', [emp,])
            return HttpResponse(json_data, content_type='application/json')
    

    【讨论】:

      猜你喜欢
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 2019-08-19
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多