我正在写Django的视图,以检查是否提供了有效的专辑ID。但是它看起来很麻烦且难以阅读。我想使其更具可读性和简短性。我无法直接检查newA.id <> a.id
。如果为空,则会显示错误。
data['id']
答案 0 :(得分:1)
整个问题似乎是当id
在data
中不是有效条目时该怎么办。
查看您的代码,尤其是下面的代码,看来id
值小于1是无效的。
if id < 1:
return Response({'message': 'Valid album id is required'})
此外,try...except
意味着,如果id
不是data
的一部分,那么这也是无效的。
这意味着可以使用默认值来简化代码,例如:
def post(self, request):
if len(request.body) > 0:
data = json.loads(request.body.decode('utf-8'))
else:
return Response({'message': 'Album id is required'})
id = int(data.get('id', 0))
if id < 1:
return Response({'message': 'Valid album id is required'})
album = Album.objects.get(pk=id)
# f-strings below are a python 3
return Response({'message': f'The album you have requested is {album}'})
上面的摘录的重要部分是:data.get('id', 0)
如果data['id']
是有效字段,则返回id
;如果在id
中找不到data
,则返回0。
不相关,因为两者都是检查request.body
的有效方法,但是更Python化的方法是像@ juanpa.arrivillaga建议的那样进行操作,即:
if request.body:
为了进一步简化它,我将通过这种方式减少一些重复:
def post(self, request):
if request.body:
data = json.loads(request.body.decode('utf-8'))
id = int(data.get('id', 0))
if id < 1:
return Response({'message': 'Valid album id is required'})
album = Album.objects.get(pk=id)
# f-strings below are a python 3
return Response({'message': f'The album you have requested is {album}'})
return Response({'message': 'Album id is required'})
答案 1 :(得分:1)
尝试提高可读性时要记住的两件事是不要过早优化和使用函数封装逻辑(尤其是如果该逻辑可能必须将来可以重复使用。
所以,只是一个简单的例子:
# Define the characters to search for as an array of [char] instances ([char[]])
# Note the absence of `@(...)`, which is never needed for array literals,
# and the absence of `;`, which is only needed to place *multiple* statements
# on the same line.
[char[]] $terms = '#', ';', '$', '|'
# The string to search trough.
# Note the use of '...' rather than "...",
# to avoid unintended expansion of "$"-prefixed tokens as
# variable references.
$StringToBeSearched = 'ABC$DEFG#'
# Use the [string] type's .IndexOfAny() method to find the first
# occurrence of any of the characters in the `$terms` array.
$StringToBeSearched.IndexOfAny($terms) # -> 3
您可以采取不同的方法。例如,可以使用def post(self, request):
if request.body:
data = json.loads(request.body.decode('utf-8'))
else:
return Response({'message': 'Album id is required'})
if _validate_data(data):
id_ = int(data['id'])
album = Album.objects.get(pk=id_)
# probably want to return a Response as well...
else:
return Response({'message': 'Valid Album id is required'})
def _validate_data(data):
if 'id' not in data:
return False
try:
id_ = int(data['id'])
except ValueError:
return False
return id_ >= 1
代替_validate_data
,当_extract_id
无效时返回None
,否则返回data
,然后检查该值,因此像这样:
id_
对于其余的代码和要遵循的任何标准,您必须决定更有意义的事情。
顺便说一句,这似乎对我来说不是一个帖子,因为似乎您只是在检索数据,即按ID的相册,POST通常用于创建新资源。