【问题标题】:What is the alternative of passing array to the URL?(URL too long)将数组传递给 URL 的替代方法是什么?(URL 太长)
【发布时间】:2021-01-22 04:42:59
【问题描述】:

当从 GET 方法请求时,url 的创建方式类似于

<your_url>?paths=path1&paths=path2&paths=path3...

如果有大量路径,这可能会很长。

我想通过 POST 方法请求路径,因为 GET 方法创建的 url 中的请求行太大。有没有替代品

request.GET.getlist('paths')

如果路径很长,则显示 Bad Request, Request Line too large。

有一个替代方案:

request.POST.getlist('paths')

在模板中传递查询字符串中的数据以使url不会很长并且可以下载所有文件的等效方法是什么?

views.py

def test_download(request):
    paths = request.GET.getlist('paths')
    context ={'paths': paths}
    response = HttpResponse(content_type='application/zip')
    zip_file = zipfile.ZipFile(response, 'w')
    for filename in paths:
         zip_file.write(filename)
    zip_file.close()
    response['Content-Disposition'] = 'attachment; filename='+'converted files'
    return response

模板

<a href ="{% url 'test_download' %}?{% for path in paths %}paths={{ path|urlencode }}&{% endfor %}">Converted Files</a>

【问题讨论】:

  • 我觉得你可以设计得更好,在 get 请求中包含 1 个路径而不是多个。理想情况下,这应该可以解决问题。在前端,您可以遍历路径并对每个路径进行 GET 调用。
  • 那么下载链接会有所不同,我已经从这些路径中压缩了文件。

标签: python django django-views django-templates request


【解决方案1】:

您可以使用表单而不是超链接来提交 POST 请求并在 POST 数据中发送您的路径。示例代码见下文

<form method="POST" action="{% url 'test_download' %}">
    {% csrf_token %}
    {% for path in paths %}
        <input type="hidden" name="paths" value="{{ path }}"
    {% endfor %}
    <button type="submit">Converted Files</button>
</form>

【讨论】:

  • 我需要创建一个单独的表单来存储路径吗?当我点击提交时,它应该下载但它显示 CSRF 验证失败。
  • 您需要在表单中添加 crsf 令牌。我忘记了。刚刚编辑了答案,在表单中添加了{% csrf_token %}
  • 你好,Minh,我需要你的帮助 stackoverflow.com/questions/67156152/…
猜你喜欢
  • 2021-08-28
  • 1970-01-01
  • 2020-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 2013-07-20
  • 2019-06-19
相关资源
最近更新 更多