Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django视图中处理ajax请求的最佳方法_Python_Django - Fatal编程技术网

Python 在django视图中处理ajax请求的最佳方法

Python 在django视图中处理ajax请求的最佳方法,python,django,Python,Django,让我们假设,在web页面中有ajax请求,它将不同的参数发送到django视图(例如,通过POST) 例如: 乘积(整数列表) 产品参数(字符串列表) 两个列表的长度必须相同 确保数据正确的最佳方法是什么 以下是处理此请求的伪代码 if 'products' and 'products_params' in request.POST and request.is_ajax(): try: products = [int(p) for p in request.POST

让我们假设,在web页面中有ajax请求,它将不同的参数发送到django视图(例如,通过POST)

例如:

  • 乘积(整数列表)
  • 产品参数(字符串列表)
两个列表的长度必须相同

确保数据正确的最佳方法是什么

以下是处理此请求的伪代码

if 'products' and 'products_params' in request.POST and request.is_ajax():
    try:
        products = [int(p) for p in request.POST['products']]
    except ValueError:
        return HttpResponseBadRequest()
    products_params = request.POST['products_params']
    if len(products) != len(products_params):
        return HttpResponseBadRequest()
    # ok, data is correct, now we can process it
有更好的方法吗?如何确保我们不会因为提供给视图的无效数据而出现意外异常

另外,这只是ajax处理。没有表单显示给用户。

关于:

    products = [int(p) for p in request.POST['products'] if str(p).isdigit()]

我推荐第一种,因为如果您使用ñ例如
unicode
将抛出错误

您的代码可以如下所示:

if request.is_ajax():
    products = [int(p) for p in request.POST.get('products',[]) if str(p).isdigit()]
    products_params = request.POST.get('products_params', [])
    if (not (products and products_params)) or (len(products) != len(products_params)):
        return HttpResponseBadRequest()

is request.is_ajax()not request.is_ajax使用表单怎么样?在这种情况下,这只是ajax处理。它并没有回答整个问题。我认为这回答了如何确保我们不会因为提供给视图的无效数据而出现意外异常?是的,确实如此。但是验证的其他部分呢?好的,这似乎适合我。
if request.is_ajax():
    products = [int(p) for p in request.POST.get('products',[]) if str(p).isdigit()]
    products_params = request.POST.get('products_params', [])
    if (not (products and products_params)) or (len(products) != len(products_params)):
        return HttpResponseBadRequest()