本文介绍了如何使用 POST 方法与 Django 中的外部 API 进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从我的导师那里得到了帮助,以找出 GET 命令.我正在努力使用 POST 命令.

I received help from my instructor to figure out the GET command. I am struggling with the POST command.

-查看-

from django.shortcuts import render
from django.shortcuts import redirect
from django.contrib import messages
import json
import requests
from ast import literal_eval
from django.shortcuts import redirect
from rest_framework.views import APIView
from rest_framework.response import Response

def add_question(request):
    if request.method == 'POST':
        url = 'http://localhost:3000/questions/'
        payload = {'content':request.POST.get("content"), 'category':request.POST.get("category")}
        res = requests.post(url, data = (payload))
        print(res)
    return Response(res.json())

我的部分问题是之前发布的关于这个主题的大部分建议已经超过 3 年了.我认为rest_framework"模块不再用于此目的.很难说.

Part of my problem is that most of the previously published advice on this topic is over 3 years old. I don't think the 'rest_framework' module is used much for this purpose anymore. It's hard to tell.

现在我得到的错误是:raise JSONDecodeError(Expecting value", s, err.value) from Nonejson.decoder.JSONDecodeError:期望值:第 1 行第 1 列(字符 0)POST/add_question HTTP/1.1";500 92794"

Right now the error I am getting is: "raise JSONDecodeError("Expecting value", s, err.value) from Nonejson.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) "POST /add_question HTTP/1.1" 500 92794"

对我有用的 GET 方法是这样的:

The GET method that worked for me was this:

def home(request):
    if request.method == 'GET':
        print('home')
    api_request = requests.get("http://localhost:3000/questions/")#.json()
    try:
        print( 'api_request='+str(api_request))
        q = literal_eval(api_request.content.decode('utf8'))
        print('q=', q, type(q))
        print( q['data'])
        json_obj = json.dumps(q['data'])
        print('json_obj=', json_obj, type(json_obj))

        #api = json.loads(api_request.content)
        api = json.loads(json_obj)
    except Exception as e:
        print( 'Exception e='+str(e))
        api = "Error..."
    else:
        if request.method == 'POST':
            post_request = requests.post("http://localhost:3000/questions/")
            print(post_request)
    return render(request, 'frontend/home.html', {'api': api})

我使用的 API 是我在 Node.js 中创建的.当我尝试发帖时,我从 Node 收到的错误是:"ReferenceError: question is not defined在 addQuestion (file:///C:/nodepract/Project05/api/routes/questions.js:60:47)"

The API I am using is one I created in Node.js. The error I am getting from Node when I attempt the post is: "ReferenceError: question is not definedat addQuestion (file:///C:/nodepract/Project05/api/routes/questions.js:60:47)"

我将视图更改为以下内容.

I changed the view to the following.

def add_question(request):
    if request.method == 'POST':
        url = 'http://localhost:3000/questions/'
        data = json.dumps(request.POST)
        res = requests.post(url, data)
        print("res.text = " + res.text)
        return Response(res.json())

当前出现以下错误.参考错误:问题未定义"

Currently getting following error."ReferenceError: question is not defined"

推荐答案

抛出异常是因为您从外部 API http://localhost:3000/questions/ 接收的数据不是JSON 数据.

The exception is thrown because the data that you receive from the external API http://localhost:3000/questions/ is not JSON data.

要调试响应,请在 res.json 调用之前打印 res.text.

To debug the response, print the res.text before res.json call.

这篇关于如何使用 POST 方法与 Django 中的外部 API 进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:13