大多数pythonic检查表单是否有数据的方式

时间:2017-03-04 06:08:42

标签: python django django-templates django-views

我目前正在学习Django,但是我对如何使用它构建相当于add方法感到很沮丧。我正在创建一个URL缩短器,并且我在以下方法之间实现创建缩短的URL:

def shorten(request):
if request.method == 'POST':
    http_url = request.POST.get("http_url","")

    if http_url: # test if not blank
        short_id = get_short_code()
        new_url = Urls(http_url=http_url, short_id=short_id)
        new_url.save()

        return HttpResponseRedirect(reverse('url_shortener:index'))
    else:
        error_message = "You didn't provide a valid url"
        return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })

return render(request, 'url_shortener/shorten.html')

VS

def shorten(request):
    http_url = request.POST["http_url"]
    if http_url:
        short_id = get_short_code()
        new_url = Urls(http_url=http_url, short_id=short_id)
        new_url.save()
        return HttpResponseRedirect(reverse('url_shortener:index'))

    else:
        error_message = "You didn't provide a valid url"
        return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })

    return render(request, 'url_shortener/shorten.html')

具体来说,我想知道以下最佳做法:

  1. 如果方法发布或http_url = request.POST["http_url"]足够
  2. ,最好是明确测试
  3. 是否建议使用http_url = request.POST.get("http_url","")或者这只是抑制错误?
  4. 如果不建议使用(2),如何使http_url成为必需项并抛出错误?我也尝试了以下内容,但是当我提交空白表单时,不会触发except块

    def shorten(request):
        if request.method == 'POST':
            try:
                http_url = request.POST["http_url"]
                short_id = get_short_code()
                new_url = Urls(http_url=http_url, short_id=short_id)
                new_url.save()
    
                return HttpResponseRedirect(reverse('url_shortener:index'))
            except KeyError:
                error_message = "You didn't provide a valid url"
                return render(request, 'url_shortener/shorten.html', { 'error_message' : error_message })
    
        return render(request, 'url_shortener/shorten.html')
    

1 个答案:

答案 0 :(得分:0)

request.POST["key"]
当词典中不存在KeyError时,

将抛出key。您可以使用try...catch子句来处理错误。

一般来说,它的惯用性和完全正常的做法:

request.POST.get("key")

有关获取here的更多信息。