Django:通过视图而不是Postman调用REST API

时间:2018-06-16 08:01:51

标签: django

我的桌面上有一个工作的python代码,可以完美地打印和制作PDF。我想要做的就是使用该代码并使用Django来允许用户输入值。

我的代码使用docusign API来调用数据。我使用需要密钥和其他参数的postman来使用API​​。我的用户输入的值将决定他们获得的数据。

我认为我必须做的是重写我的代码,把它放在某处,然后把它变成一个视图。该视图将发送到模板。

编辑 -

我的代码:

# Get Envelope Data- use account ID from above
# Get Todays Date, Daily Setting
day = datetime.datetime.today().strftime('%Y-%m-%d')

url = "https://demo.docusign.net/restapi/v2/accounts/" + accountId + "/envelopes"
# if Envelope is completed
querystring = {"from_date": Date, "status": "completed"}


headers = {
    'X-DocuSign-Authentication': "{\"Username\":\""+ email +"\",\"Password\":\""+Password+"\",\"IntegratorKey\": \""+IntegratorKey+"\"}",
    'Content-Type': "application/json",
    'Cache-Control': "no-cache",
    'Postman-Token': "e53ceaba-512d-467b-9f95-1b89f6f65211"
}

response = requests.request("GET", url, headers=headers, params=querystring)
envelopes = response.text

抱歉,让我再试一次。我目前在桌面上有一个python3程序。我用idle运行它,一切都是我想要的。

我想用Django做的是使用此代码在网页上打印其输出,并让用户下载它的附加csv文件输出。我已经设法制作了一个Django localhost,我就陷入了困境。我不知道如何使用我的python3代码运行到网页。

代码由API调用组成,我使用postman帮助我发送正确的参数。我将添加一张代码图片。我想要的只是让用户输入accountID等值,以便API可以完成请求并为他们自己的请求提供数据。

1 个答案:

答案 0 :(得分:0)

我将尝试向您概述如何使用Django。

您可以form获取用户account_id

class AccountForm(forms.Form):
    account_id = forms.IntegerField()

您可以通过通用FormView显示此表单(另请参阅this):

class AccountView(views.FormView):
    form_class = AccountForm
    template_name = 'account.html'

    def form_valid(self, form):
        # here you make your request to the external API
        account_id = form.cleaned_data['account_id']
        url = "https://demo.docusign.net/restapi/v2/accounts/" + account_id + "/envelopes"
        headers = ...
        querystring = ...
        resp = requests.request("GET", url, headers=headers, params=querystring)

        ctx = {
            'result': resp.text,
        }
        return render(self.request, 'result.html', ctx)

我这里不显示模板account.html。你必须自己想出那个;我提供的链接应该指向正确的方向。

现在,还有待确定的方法是form_valid应该返回的具体内容。我展示的代码在上下文中呈现了带有API调用响应的模板,因此在模板result.html中,您可以按照自己喜欢的方式显示结果数据。

您也提到过下载CSV文件。这可能是一个不同的视图,可能是由result.html中的链接或按钮触发的。