【问题标题】:Most pythonic way of checking if a form submiited has data检查提交的表单是否有数据的大多数pythonic方法
【发布时间】:2017-07-24 09:12:30
【问题描述】:

我目前正在学习 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')

对比

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. 明确测试方法是 post 还是 http_url = request.POST["http_url"] 是否足够的最佳实践
  2. 是推荐使用http_url = request.POST.get("http_url","")还是只是为了抑制错误?
  3. 如果不推荐 (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')
    

【问题讨论】:

  • Django 有一个完整的表单框架,正是为此而设计的。你应该使用它。
  • 是的,我认为基于类的视图适合于此,但为了简单起见,我决定坚持使用request.POST.get("key")。我会想出很多复杂的项目来实施 CBV。谢谢!

标签: python django django-templates django-views


【解决方案1】:
request.POST["key"]

当字典中不存在key 时,将抛出KeyError。您可以使用try...catch 子句来处理错误。

不过,一般来说,这样做是惯用且完全正常的:

request.POST.get("key")

更多关于获取here

【讨论】:

  • 谢谢!我决定坚持使用request.POST.get("key"),因为这只是一个简单的项目。一旦我有一个非常复杂的项目要处理,我将实现基于类的视图:)
猜你喜欢
  • 2019-05-04
  • 2012-03-01
  • 2014-06-13
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
相关资源
最近更新 更多