我创建了以下序列化程序,其中我两次调用函数_calculate_image_dimensions。现在,我尝试了@仙人掌属性,但由于必须传递值width, height,所以无法工作。但是,对于get_width和get_height,它们不会改变。是否有办法确保计算只计算一次?
class IntegrationImageSerializer(serializers.ModelSerializer):
width = serializers.SerializerMethodField()
height = serializers.SerializerMethodField()
class Meta:
model = IntegrationImage
fields = ("image", "width", "height")
def _calculate_image_dimensions(self, width, height) -> int:
MAX_IMAGE_SIZE = 350
aspect_ratio = width / height
if width > height:
width = MAX_IMAGE_SIZE
height = width / aspect_ratio
else:
height = MAX_IMAGE_SIZE
width = height * aspect_ratio
return round(width), round(height)
def get_width(self, obj: IntegrationImage) -> int:
width, height = self._calculate_image_dimensions(
obj.image.width, obj.image.height
)
return width
def get_height(self, obj: IntegrationImage) -> int:
width, height = self._calculate_image_dimensions(
obj.image.width, obj.image.height
)
return height发布于 2020-10-08 16:54:38
最初,我觉得有点困惑,有一个方法get_width执行一个函数,得到宽度和高度,然后只返回width。
使用dimensions字段稍微改变API结构是否有意义(如果width和height被引用到很多地方,这实际上可能并不有效)?
如果不需要更改对width和height的大量引用,这将只调用_calculate_image_dimensions一次(我认为这就是您要解决的问题?)你就不需要缓存了。
class IntegrationImageSerializer(serializers.ModelSerializer):
dimensions = serializers.SerializerMethodField()
class Meta:
model = IntegrationImage
fields = ("image", "dimensions")
def _calculate_image_dimensions(self, width, height) -> int:
MAX_IMAGE_SIZE = 350
aspect_ratio = width / height
if width > height:
width = MAX_IMAGE_SIZE
height = width / aspect_ratio
else:
height = MAX_IMAGE_SIZE
width = height * aspect_ratio
return round(width), round(height)
def get_dimensions(self, obj: IntegrationImage) -> int:
width, height = self._calculate_image_dimensions(
obj.image.width, obj.image.height
)
return {"width": width, "height": height}发布于 2020-10-08 16:35:44
使它成为一个免费的函数(类外),并用lru_cache()装饰它
from functools import lru_cache
@lru_cache(maxsize=None)
def calculate_image_dimensions(width, height) -> int:
MAX_IMAGE_SIZE = 350
aspect_ratio = width / height
if width > height:
width = MAX_IMAGE_SIZE
height = width / aspect_ratio
else:
height = MAX_IMAGE_SIZE
width = height * aspect_ratio
return round(width), round(height)这将缓存工作进程生存期的结果。
(不过,我怀疑有几个比较和分区的函数是应用程序的性能瓶颈。)
https://stackoverflow.com/questions/64266839
复制相似问题