美文网首页
serializer重写FileField

serializer重写FileField

作者: forjie | 来源:发表于2019-07-15 11:53 被阅读0次

    我们图片用的服务器和代码服务器不是同一个,返回给前端的url就需要替换host

    1.查看源码里面FileField怎么给服务器返url的,在里面替换host就行

        def to_representation(self, value):
            if not value:
                return None
    
            use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL)
    
            if use_url:
                if not getattr(value, 'url', None):
                    # If the file has not been saved it may not have a URL.
                    return None
                url = value.url
                request = self.context.get('request', None)
                if request is not None:
                    return request.build_absolute_uri(url)
                return url
            return value.name
    

    2.重写to_representation,替换原先的host

    from rest_framework import serializers
    class FileField(serializers.FileField):
            def to_representation(self, value: Any) -> Any:
            if not value:
                return None
    
            use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL)
            host = getattr(self, 'host', settings.NEW_FILES_HOST)
    
            if use_url:
                if not getattr(value, 'url', None):
                    # If the file has not been saved it may not have a URL.
                    return None
                url = value.url
                request = self.context.get('request', None)
                if request is not None:
                    # 拿到当前的本机ip
                    original_host = request.get_host()
                    url = request.build_absolute_uri(url)
                    if host:
                        # 替换成新的域名
                        url = url.replace(original_host, host)
                return url
            return value.name
    

    相关文章

      网友评论

          本文标题:serializer重写FileField

          本文链接:https://www.haomeiwen.com/subject/pfogkctx.html