【问题标题】:Django, handle Response from external serverDjango,处理来自外部服务器的响应
【发布时间】:2016-07-24 21:36:04
【问题描述】:

问题是如何处理来自外部服务器的 HttpResponce?

想法是我将json数据发送到外部服务器

(例如搜索数据{'keyword': keyword, 'limit':limit, 'db':db}

response = requests.post(url, json = userupload, headers=headers)

之后我从服务器收到带有 json 数据的响应

return HttpResponse(response)

它在屏幕上,但你可以理解,这对用户来说不是很好的视图......

例如,我怎样才能将这些数据添加到适当的 html 表中? (最好的选择是如果我可以在同一页上打印出来)

【问题讨论】:

  • 如果您不需要“中间人”,为什么不使用 javascript?我不太确定你想达到什么目标,但这个:docs.python-requests.org 可能有帮助吗?

标签: json django httprequest httpresponse


【解决方案1】:

如果我理解正确,您希望将 JSON 格式的 post 请求的输出呈现为 HTML 文件。

为此,将 json 编码的对象从视图传递到模板:

views.py:

import json

def myview(request):
    obj = requests.post(url, json = userupload, headers=headers)
    return render_to_response("template.html", {"obj_as_json": json.dumps(obj.json())})

template.html:

<html>
    <head>
    <script type="text/javascript">
    var obj = {{ obj_as_json }};
    </script>
    </head>
    ...
</html>

【讨论】:

    【解决方案2】:

    https://docs.djangoproject.com/en/1.9/intro/tutorial03/ 在 django 教程中,您将学习如何使用 html 和上下文数据呈现响应。

    如果你使用requests,你可以这样做:

    response = requests.api.post(...
    context = json.loads(response.json())
    return render(request, 'index.html', context)
    

    json api 的一大优点是您可以使用 javascript 异步访问它。如果您只想呈现响应而不调用数据库来操作来自 json api 的数据,则应该考虑这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-30
      • 1970-01-01
      • 2016-06-05
      • 2013-02-11
      相关资源
      最近更新 更多