【问题标题】:Should I use GET or POST to retrieve results Django我应该使用 GET 还是 POST 来检索结果 Django
【发布时间】:2016-05-25 07:13:15
【问题描述】:

我正在使用 Django 并有一个视图来获取/插入数据库中的一些记录。这是我的代码:

class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
    content = JSONRenderer().render(data)
    kwargs['content_type'] = 'application/json'
    super(JSONResponse, self).__init__(content, **kwargs)

@api_view(('GET','POST'))
@renderer_classes((TemplateHTMLRenderer,))
@csrf_exempt
def cours_list(request):

    if request.method == 'GET':
       data = JSONParser().parse(request)
       results = Lesson.objects.get(discipline=data.discipline)
       return Response({'cours': results}, template_name='search_results.html')

    elif request.method == 'POST':
       data = JSONParser().parse(request)
       serializer = LessonSerializer(data=data)
       if serializer.is_valid():
           serializer.save()
           return JSONResponse(serializer.data, status=201)
       return JSONResponse(serializer.errors, status=400)

因此,我使用 GET 获取数据并使用 POST 插入新记录。首先,这是正确的做法吗?我读过一次,无论在什么情况下使用 GET 都不是一个坏主意。 此外,GET 代码实际上并没有工作(我收到一个错误的请求错误),这似乎来自无法解析请求的 JSONParser。

编辑1

这是发送的请求:

GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}

编辑2

我尝试打印requet.GET,它给出的结果如下:

<QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>

当尝试访问request.data['discipline'] 时,它会说:

django.utils.datastructures.MultiValueDictKeyError: "'discipline'"

【问题讨论】:

  • 我想建议你发布你的整个视图,因为不清楚你是否正在尝试使用常规的 Django 视图函数,或者如果你想使用 Django REST Framework 的 JSONParser 等如果你可以发布一个curl 用于发送请求的命令(它可以帮助其他人重现您的问题,以便他们为您提供帮助)
  • @Bakkel。我确实在尝试使用 Django REST。

标签: python json django rest


【解决方案1】:

一般情况下使用GET方式获取信息,见HTTP/1.1: Method Dediniton, 9.3

GET 方法意味着检索任何信息(以 entity) 由 Request-URI 标识。如果 Request-URI 指的是 一个数据产生过程,它是产生的数据,应该是 作为响应中的实体而不是源文本返回 进程,除非该文本恰好是进程的输出。

对于 POST 方法,最好使用 POST 请求提交新数据,请参阅HTTP/1.1: Method Dediniton, 9.5

POST 方法用于请求源服务器接受 包含在请求中的实体作为资源的新下属 由 Request-Line 中的 Request-URI 标识。 POST 旨在 允许一个统一的方法覆盖以下功能:

  ................................................................
  - Providing a block of data, such as the result of submitting a
    form, to a data-handling process;
  - Extending a database through an append operation.

另外,看看Which HTTP methods match up to which CRUD methods?,它会让您更清楚地了解如何以及何时使用特定的 HTTP 方法,并帮助您进行下一步的开发

【讨论】:

    【解决方案2】:

    我应该使用 GET 还是 POST 来检索结果 Django

    使用 GET 检索

    我曾经读到,无论在什么情况下使用 GET 都不错

    完全没有,只要您的 GET 操作不包含副作用(例如,在您的 GET 方法中,您只是从数据库中读取数据。

    GET 代码实际上不起作用(我收到一个错误的请求错误)

      data2 = JSONParser().parse(request) # you used data2
      results = Lesson.objects.get(discipline=data.discipline) # and you used data
                                              ^
                                              |____ data? data2?
    

    您没有正确传递 GET 参数

    你需要像这样传递 GET 参数url/?param1=value1 要读取该值,请使用 param1 = request.GET['param1'] 和 param1 将是字符串 value1

    你正在做的不是传递一个值:

    GET http://127.0.0.1:8000/cours/?{%22discipline%22:%22Mathematiques%22,%22localisation%22:%22%22}

    这就是为什么你得到一个空值['']

    <QueryDict: {'{"discipline":"Mathematiques","localisation":""}': ['']}>
    

    如果需要,您可以将整个数据作为 JSON 字符串传递,但我更喜欢这样分解:

    url/?discipline=Mathematiques&amp;localisation=Quelquechose

    discipline = request.GET['discipline']
    localisation = request.GET['localisation']
    

    【讨论】:

    • 谢谢 Bakkal,我现在明白了。我编辑了帖子,这是一个错误。我仍然有一个似乎不起作用的解析函数错误。
    • 我想你想解析(request.GET)或解析(request.data),而不是解析(请求),你能试试吗?
    • 我都试过了,它说QueryDict has no attribute read
    • 可以直接从QueryDict获取参数,也可以正确使用JSONParser:django-rest-framework.org/api-guide/parsers/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多