Post request to external Rest Service using Django - use returned json to update model

浪尽此生 提交于 2020-05-17 06:57:10

问题


I require some advice on the best way to implement the following details using Camunda Rest API and Django:

1) User is presented with a form - Selects the details and then does a POST request to camunda using 'http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start'

the details sent in this POST request consist of 3 variables in a JSON RAW : in the form of :

{"variables":
    {"UserID" : {"value" : "user.", "type": "String"},
     "OrganisationID" : {"value" : "some value", "type": "String"}
    },
     "businessKey" : "SomeBusinessKey"
    }

from views.py

from django.shortcuts import render from django.views.generic import TemplateView from .forms import StartProject

 import requests

 class StartProcessView(TemplateView):

    template_name = 'startdeliveryphase.html'

    def get(self, request):
        form = StartProject()
        return render(request, self.template_name, {'form':form})





    def post(self,request):
        form = StartProject()
        url = "http://localhost:8080/engine-rest/process-definition/key/Process_B_PerProject/start"
        payload = "{\"variables\":\r\n    {\"Username\" : {\"value\" : \"[form.Username]\", \"type\": \"String\"},\r\n     \"OrganisationInitiating\" : {\"value\" : \"[form.OrganisationInitiator]\", \"type\": \"String\"}},\r\n     \"businessKey\" : {form.businessKey}\r\n    }"
        headers = {
        'Content-Type': 'application/json'
        }
        response = requests.request("POST", url, headers=headers, data = payload)
        return render(response, self.template_name, {'form':form})

The response is returned as a 200 along with a JSON payload in the form:

 {
    "links": [
        {
            "method": "GET",
            "href": "http://localhost:8080/engine-rest/process-instance/fbff8359-84cd-11ea-a2e1-00155d891509",
                "rel": "self"
            }
        ],
        "id": "fbff8359-84cd-11ea-a2e1-00155d891509",
        "definitionId": "Process_B_PerProject:1:71921815-737c-11ea-91a6-00155d891509",
        "businessKey": "SomeBusinessKey",
        "caseInstanceId": null,
        "ended": false,
        "suspended": false,
        "tenantId": null
}

Question 1 - from this part - how do I get the variables from the form into the payload: the method I have tried gets a 500 response - so something going wrong here.

Question 2 - what is the method to use the response to update a model?


回答1:


Question 1: Use response.json() to get json from response, review Request doc

Question 2: For save use create or update method Create or update django



来源:https://stackoverflow.com/questions/61373480/post-request-to-external-rest-service-using-django-use-returned-json-to-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!