我目前正在学习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')
具体来说,我想知道以下方面的最佳实践:
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')
当字典中不存在
key
时,将抛出一个KeyError
。您可以使用try...catch
子句来处理错误。你知道吗但一般来说,这是一个惯用且非常正常的做法:
有关获取here的详细信息。你知道吗
相关问题 更多 >
编程相关推荐