Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .chronus/changes/http-client-python-model-query-expansion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
changeKind: fix
packages:
- "@typespec/http-client-python"
---

Serialize named model query parameters using form-style expansion, including exploded properties and query continuation routes.
3 changes: 3 additions & 0 deletions packages/http-client-python/emitter/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,9 @@ export function isAbstract<TServiceOperation extends SdkServiceOperation>(
export function getDelimiterAndExplode(
parameter: SdkQueryParameter | SdkHeaderParameter,
): [string | undefined, boolean] {
if (parameter.kind === "query" && parameter.type.kind === "model") {
return [undefined, parameter.explode];
}
if (parameter.type.kind !== "array") return [undefined, false];
let delimiter: string | undefined = undefined;
let explode = parameter.kind === "query" && parameter.explode;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
ClientParameter,
ConfigParameter,
ParameterType,
ModelType,
)
from ..models.parameter import _ParameterBase
from ..models.parameter_list import BodyParameterType
Expand Down Expand Up @@ -164,11 +165,24 @@ def serialize_query_header(
f""" _headers[{python_string_literal(header_name)}] = _SERIALIZER.header("if_none_match", if_none_match, "str")""",
]

set_parameter = "_{}[{}] = {}".format(
kwarg_name,
python_string_literal(param.wire_name, quote="'"),
self.serialize_parameter(param, serializer_name),
)
if not is_legacy and param.location == ParameterLocation.QUERY and isinstance(param.type, ModelType):
serialized_model = (
f"{serializer_name}.query_model({python_string_literal(param.full_client_name)}, "
f"{param.full_client_name}, skip_quote={param.skip_url_encoding})"
)
if param.explode:
set_parameter = f"_{kwarg_name}.update({serialized_model})"
else:
set_parameter = (
f"_{kwarg_name}[{python_string_literal(param.wire_name)}] = "
f"','.join(component for pair in {serialized_model}.items() for component in pair)"
)
else:
set_parameter = "_{}[{}] = {}".format(
kwarg_name,
python_string_literal(param.wire_name, quote="'"),
self.serialize_parameter(param, serializer_name),
)
# When the body is optional, the content-type may legitimately be ``None`` (no body
# was sent). In that case the header must be omitted instead of serialized, otherwise
# ``_SERIALIZER.header`` raises ``ValueError: No value for given attribute``.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -748,6 +748,26 @@ class Serializer: # pylint: disable=too-many-public-methods
raise TypeError("{} must be type {}.".format(name, data_type)) from exc
return str(output)

def query_model(self, name, data, **kwargs):
"""Serialize a model's wire-name/value pairs for form-style query expansion.

:param str name: The name of the query parameter.
:param Mapping data: The model or mapping to serialize.
:keyword bool skip_quote: Whether to skip URL encoding.
:return: Individually encoded property names and values.
:rtype: dict[str, str]
:raises ValueError: if data is None.
"""
if data is None:
raise ValueError("No value for given attribute: {}".format(name))
return {
self.query(name, key, "str", **kwargs): self.query(
name, value, "bool" if isinstance(value, bool) else "str", **kwargs
)
for key, value in data.items()
if value is not None
}

def header(self, name, data, data_type, **kwargs):
"""Serialize data intended for a request header.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import pytest
import pytest_asyncio
from routes.aio import RoutesClient
from routes.models import ExpandParameters


@pytest_asyncio.fixture
Expand All @@ -19,6 +20,14 @@ async def test_fixed(client: RoutesClient):
await client.fixed()


@pytest.mark.asyncio
@pytest.mark.parametrize("expansion", ["query_expansion", "query_continuation"])
@pytest.mark.parametrize("style", ["standard", "explode"])
async def test_query_parameters_model(client: RoutesClient, expansion: str, style: str):
operation = getattr(getattr(client.query_parameters, expansion), style)
await operation.model(param=ExpandParameters(field="status", value="active"))


@pytest.mark.asyncio
async def test_in_interface_fixed(client: RoutesClient):
await client.in_interface.fixed()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# --------------------------------------------------------------------------
import pytest
from routes import RoutesClient
from routes.models import ExpandParameters


@pytest.fixture
Expand Down Expand Up @@ -213,6 +214,13 @@ def test_query_parameters_annotation_only(client: RoutesClient):
)


@pytest.mark.parametrize("expansion", ["query_expansion", "query_continuation"])
@pytest.mark.parametrize("style", ["standard", "explode"])
def test_query_parameters_model(client: RoutesClient, expansion: str, style: str):
operation = getattr(getattr(client.query_parameters, expansion), style)
operation.model(param=ExpandParameters(field="status", value="active"))


def test_query_parameters_query_expansion_standard_primitive(client: RoutesClient):
client.query_parameters.query_expansion.standard.primitive(
param="a",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from types import SimpleNamespace

import pytest
from jinja2 import Environment, PackageLoader


@pytest.fixture(scope="session", autouse=True)
def testserver():
yield


@pytest.fixture
def serializer():
env = Environment(loader=PackageLoader("pygen.codegen", "templates"))
source = env.get_template("serialization.py.jinja2").render(
code_model=SimpleNamespace(license_header="", core_library="corehttp")
)
namespace = {}
exec(compile(source, "<serialization>", "exec"), namespace)
return namespace["Serializer"]()


def test_query_model_quotes_components_and_preserves_falsy_values(serializer):
result = serializer.query_model(
"filter",
{"wire,name": "a,b & c", "enabled": False, "count": 0, "empty": "", "omitted": None},
)
assert result == {"wire%2Cname": "a%2Cb%20%26%20c", "enabled": "false", "count": "0", "empty": ""}


def test_query_model_skip_url_encoding(serializer):
assert serializer.query_model("filter", {"wire,name": "a,b"}, skip_quote=True) == {"wire,name": "a,b"}


def test_query_model_rejects_missing_required_model(serializer):
with pytest.raises(ValueError, match="filter"):
serializer.query_model("filter", None)
Loading