def _get_uri_from_request(request):
    """
    The uri returned from request.uri is not properly urlencoded
    (sometimes it's partially urldecoded) This is a weird hack to get
    sanic to return the proper urlencoded string uri
    """
    uri = request._parsed_url.path
    if request._parsed_url.query:
        uri = uri + b'?' + request._parsed_url.query
    try:
        server_name = request.server_name
        server_port = request.server_port
        scheme = request.scheme
    except (AttributeError, NotImplementedError):
        override_server_name = request.app.config.get('SERVER_NAME', False)
        requested_host = request.host
        server_name = override_server_name or request.headers.get(
            'x-forwarded-host') or requested_host.split(':')[0]
        forwarded_port = (override_server_name.split(':')[1] if 
            override_server_name and ':' in override_server_name else None
            ) or request.headers.get('x-forwarded-port') or (requested_host
            .split(':')[1] if ':' in requested_host else None)
        try:
            server_port = (int(forwarded_port) if forwarded_port else None
                ) or request._parsed_url.port or request.transport.get_extra_info(
                'sockname')[1]
        except NotImplementedError:
            server_port = 80
        scheme = request.headers.get('x-forwarded-proto') or request.scheme
    if ':' in server_name:
        server_name, server_port = server_name.split(':', 1)
    include_port = True
    if scheme == 'https' and server_port == 443:
        include_port = False
    elif scheme == 'http' and server_port == 80:
        include_port = False
    if include_port:
        return scheme + '://' + server_name + ':' + str(server_port
            ) + uri.decode('utf-8')
    return scheme + '://' + server_name + uri.decode('utf-8')
