python - Django Rest framework - change the URL hostname in hyperlinkedmodel serializer -
i have webservice built drf 1.8.x model driven. intent provide absolute urls in response foreign key fields , includes right hostname(gateway hostname). however, since api sits behind nginx gateway, hostname field modified , sending context['request'] serializer instance doesn't seem help.
as of i'm using decorators modifying hostname , handling version based behaviour self url field forieign key fields still showing api hostname. here code below:
serializers.py
class nodeserializer(serializers.hyperlinkedmodelserializer): url = serializers.serializermethodfield() class meta: model = node fields = ('url', 'name', 'description', 'owner', 'address', 'created', 'updated', 'endpoint') extra_kwargs= { 'endpoint': {'view_name': 'loadbalancerendpoint-detail'}, 'owner': {'view_name': 'artifactowner-detail'} } @set_api_version_ref def get_url(self, obj): return self.context['request'].meta.get('http_ref')
decorator - set_api_version_ref
def set_api_version_ref(f): @functools.wraps(f) def wrapper(obj, ref): base_href = obj.context['request'].meta.get('path_info', none) http_host = obj.context['request'].meta.get('http_x_host', none) ''' parse incoming request url take api version in variable ''' version_parse = re.search('\/myapi\/v(?p<version>(1(\.[0-1])?))\/\w+', base_href) api_version = version_parse.group('version') logger.debug("api version detected: {}".format(api_version)) href_suffix = base_href+str(ref.id)+"/" if http_host: href = 'https://'+http_host+href_suffix base_path = 'https://'+http_host+'/myapi/'+api_version+"/" else: href = href_suffix base_path = '/myapi/v'+api_version+"/" logger.debug("href assembled: {}".format(href)) obj.context['request'].meta['api_version'] = api_version obj.context['request'].meta['http_ref'] = href obj.context['request'].meta['base_path'] = base_path result = f(obj, ref) return result return wrapper
passing extra_kwargs related field view names(loadbalancerendpoint-detail, artifactowner-detail etc.,) seem give me url pk, don't know way modify hostname out using decorator approach i'm doing url field. here appreciated, thanks!
Comments
Post a Comment