我目前正在学习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')
具体来说,我想知道以下最佳做法:
http_url = request.POST["http_url"]
足够http_url = request.POST.get("http_url","")
或者这只是抑制错误?如果不建议使用(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')
答案 0 :(得分:0)
request.POST["key"]
当词典中不存在KeyError
时,将抛出key
。您可以使用try...catch
子句来处理错误。
一般来说,它的惯用性和完全正常的做法:
request.POST.get("key")
有关获取here的更多信息。