【问题标题】:How to send POST request after form submit 302 in Django?如何在 Django 中提交 302 表单后发送 POST 请求?
【发布时间】:2020-11-10 11:19:42
【问题描述】:

我有一个实现如下:

  1. 有一个付款表格,用户填写所有详细信息。(API1),这里我收到错误 302:

  2. 在提交该表单时,我认为调用了其中一个函数。

  3. 在后端实现中,即。在views.py 中,我想向我已集成的网关之一发送 POST 请求。(API2)

但是问题来了,因为请求是以 GET 方式进行的,因此它会丢弃我与请求一起发送的所有表单数据。

以下是代码。

views.py -->

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
    'CustomerID': 'abc',
    'TxnAmount': '1.00',
    'BankID': '1',
    'AdditionalInfo1': '999999999',
    'AdditionalInfo2': 'test@test.test',
}


payload_encoded = urlencode(payload, quote_via=quote_plus)

response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)

content = response.url
return_config = {
    "type": "content",
    "content": redirect(content)
}
return return_config

如何将第二个请求 (API2) 作为 POST 请求连同所有参数一起发送?我在这里做错了什么?

感谢您的建议。

【问题讨论】:

  • 为什么不能在 POST 方法中执行,而不是在视图的重定向 GET 方法中执行。
  • 你为什么要返回一个重定向?您在请求后从该外部服务获得结果,您可以使用该结果生成响应。你需要看看为什么你会得到 302 状态。
  • 抱歉不清楚你想达到什么目的

标签: python-3.x django django-request


【解决方案1】:

如果请求返回 302 状态,则新 url 在response.headers['Location'] 中可用。您可以继续关注新的 url,直到得到有效的回复。

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
}
payload = {
    'CustomerID': 'abc',
    'TxnAmount': '1.00',
    'BankID': '1',
    'AdditionalInfo1': '999999999',
    'AdditionalInfo2': 'test@test.test',
}


payload_encoded = urlencode(payload, quote_via=quote_plus)

response = requests.post('https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****', data=payload_encoded, headers=headers)

while response.status_code == 302:
    response = requests.post(response.headers['Location'], data=payload_encoded, headers=headers)

content = response.text
return_config = {
    "type": "content",
    "content": content
}
return return_config

【讨论】:

    【解决方案2】:
    # here you are assigning the post url to content ie. 'https://www.billdesk.com/pgidsk/PGIMerchantRequestHandler?hidRequestId=****&hidOperation=****'
    content = response.url 
    
    return_config = {
        "type": "content",
        "content": redirect(content) # calling redirect with the response.url
    }
    

    改为:

    # check status code for response
    print(response)
     
    content = response.json() # if response is of json in format
    content = response.text   # if response is of plain text
    
    return_config = {
        "type": "content",
        "content": content 
    }
    
    return return_config
    

    request.post() 返回requests.Response 对象。为了获取响应数据,您需要使用.text.json() 访问它,具体取决于发送响应的格式。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 2018-05-16
      • 2021-10-12
      • 1970-01-01
      • 2019-01-19
      • 2020-04-18
      • 2020-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多