Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Smart text serialization #12149

Merged
merged 2 commits into from
Jun 23, 2020
Merged
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
1 change: 1 addition & 0 deletions sdk/core/azure-core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

- `AzureKeyCredentialPolicy` will now accept (and ignore) passed in kwargs #11963
- Better error messages if passed endpoint is incorrect #12106
- Do not JSON encore a string if content type is "text" #12137

## 1.6.0 (2020-06-03)

Expand Down
25 changes: 25 additions & 0 deletions sdk/core/azure-core/azure/core/pipeline/transport/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,19 @@ def set_streamed_data_body(self, data):
self.data = data
self.files = None

def set_text_body(self, data):
"""Set a text as body of the request.

:param data: A text to send as body.
:type data: str
"""
if data is None:
self.data = None
else:
self.data = data
self.headers["Content-Length"] = str(len(self.data))
self.files = None

def set_xml_body(self, data):
"""Set an XML element tree as the body of the request.

Expand Down Expand Up @@ -685,6 +698,11 @@ def _request(
# type: (...) -> HttpRequest
"""Create HttpRequest object.

If content is not None, guesses will be used to set the right body:
- If content is an XML tree, will serialize as XML
- If content-type starts by "text/", set the content as text
- Else, try JSON serialization

xiangyan99 marked this conversation as resolved.
Show resolved Hide resolved
:param str method: HTTP method (GET, HEAD, etc.)
:param str url: URL for the request.
:param dict params: URL query parameters.
Expand All @@ -703,8 +721,15 @@ def _request(
request.headers.update(headers)

if content is not None:
content_type = request.headers.get("Content-Type")
if isinstance(content, ET.Element):
request.set_xml_body(content)
# https://github.com/Azure/azure-sdk-for-python/issues/12137
# A string is valid JSON, make the difference between text
# and a plain JSON string.
# Content-Type is a good indicator of intent from user
elif content_type and content_type.startswith("text/"):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm wondering if we've created a bit of a mishmash in how we decide how to serialize/pass request bodies. We are using the Content-Type header, which parameters we pass in (form_data or content/stream_content) as well as looking at the content mixed together. For example, we will try to serialize the data as json even if I specify a completely different header (assuming I didn't pass in an Element instance that is :)). This is a reasonable first step given where we are.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'm not really happy by the black magic, it's why I took the simplest approach to avoid two much black magic: when you cannot guess at all if this is a string test, or a string token of JSON.

request.set_text_body(content)
else:
try:
request.set_json_body(content)
Expand Down
19 changes: 19 additions & 0 deletions sdk/core/azure-core/tests/test_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,25 @@ def test_request_url_with_params(self):

self.assertIn(request.url, ["a/b/c?g=h&t=y", "a/b/c?t=y&g=h"])

def test_request_text(self):
client = PipelineClientBase('http://example.org')
request = client.get(
"/",
content="foo"
)

# In absence of information, everything is JSON (double quote added)
assert request.data == json.dumps("foo")

request = client.post(
"/",
headers={'content-type': 'text/whatever'},
content="foo"
)

# We want a direct string
assert request.data == "foo"


if __name__ == "__main__":
unittest.main()