File: test_example_sansio.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (189 lines) | stat: -rw-r--r-- 7,424 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# --------------------------------------------------------------------------
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the ""Software""), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# --------------------------------------------------------------------------

import sys
from azure.core.pipeline import PipelineRequest
from azure.core.rest import HttpRequest, HttpResponse
from azure.core import PipelineClient
from azure.core.pipeline.policies import RedirectPolicy
from azure.core.pipeline.policies import UserAgentPolicy
from azure.core.pipeline.policies import SansIOHTTPPolicy
from azure.core.pipeline.policies import RequestIdPolicy


def test_example_headers_policy():
    url = "https://bing.com"
    policies = [UserAgentPolicy("myuseragent"), RedirectPolicy()]

    # [START headers_policy]
    from azure.core.pipeline.policies import HeadersPolicy

    headers_policy = HeadersPolicy()
    headers_policy.add_header("CustomValue", "Foo")

    # Or headers can be added per operation. These headers will supplement existing headers
    # or those defined in the config headers policy. They will also overwrite existing
    # identical headers.
    policies.append(headers_policy)
    client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
    request = HttpRequest("GET", url)
    pipeline_response = client._pipeline.run(request, headers={"CustomValue": "Bar"})
    # [END headers_policy]

    response = pipeline_response.http_response
    assert isinstance(response.status_code, int)


def test_example_request_id_policy():
    url = "https://bing.com"
    policies = [UserAgentPolicy("myuseragent"), RedirectPolicy()]

    # [START request_id_policy]
    from azure.core.pipeline.policies import HeadersPolicy

    request_id_policy = RequestIdPolicy()
    request_id_policy.set_request_id("azconfig-test")

    # Or headers can be added per operation. These headers will supplement existing headers
    # or those defined in the config headers policy. They will also overwrite existing
    # identical headers.
    policies.append(request_id_policy)
    client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
    request = HttpRequest("GET", url)
    pipeline_response = client._pipeline.run(request, request_id="azconfig-test")
    # [END request_id_policy]

    response = pipeline_response.http_response
    assert isinstance(response.status_code, int)


def test_example_user_agent_policy():
    url = "https://bing.com"
    redirect_policy = RedirectPolicy()

    # [START user_agent_policy]
    from azure.core.pipeline.policies import UserAgentPolicy

    user_agent_policy = UserAgentPolicy()

    # The user-agent policy allows you to append a custom value to the header.
    user_agent_policy.add_user_agent("CustomValue")

    # You can also pass in a custom value per operation to append to the end of the user-agent.
    # This can be used together with the policy configuration to append multiple values.
    policies = [
        redirect_policy,
        user_agent_policy,
    ]
    client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
    request = HttpRequest("GET", url)
    pipeline_response = client._pipeline.run(request, user_agent="AnotherValue")
    # [END user_agent_policy]

    response = pipeline_response.http_response
    assert isinstance(response.status_code, int)


def example_network_trace_logging():
    filename = "log.txt"
    url = "https://bing.com"
    policies = [UserAgentPolicy("myuseragent"), RedirectPolicy()]

    # [START network_trace_logging_policy]
    from azure.core.pipeline.policies import NetworkTraceLoggingPolicy
    import sys
    import logging

    # Create a logger for the 'azure' SDK
    logger = logging.getLogger("azure")
    logger.setLevel(logging.DEBUG)

    # Configure a console output
    handler = logging.StreamHandler(stream=sys.stdout)
    logger.addHandler(handler)

    # Configure a file output
    file_handler = logging.FileHandler(filename)
    logger.addHandler(file_handler)

    # Enable network trace logging. This will be logged at DEBUG level.
    # By default, logging is disabled.
    logging_policy = NetworkTraceLoggingPolicy()
    logging_policy.enable_http_logger = True

    # The logger can also be enabled per operation.
    policies.append(logging_policy)
    client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(base_url=url, policies=policies)
    request = HttpRequest("GET", url)
    pipeline_response = client._pipeline.run(request, logging_enable=True)

    # [END network_trace_logging_policy]
    response = pipeline_response.http_response
    assert isinstance(response.status_code, int)


def example_proxy_policy():
    # [START proxy_policy]
    from azure.core.pipeline.policies import ProxyPolicy

    proxy_policy = ProxyPolicy()

    # Example
    proxy_policy.proxies = {"http": "http://10.10.1.10:3148"}

    # Use basic auth
    proxy_policy.proxies = {"https": "http://user:password@10.10.1.10:1180/"}

    # You can also configure proxies by setting the environment variables
    # HTTP_PROXY and HTTPS_PROXY.
    # [END proxy_policy]


def test_example_per_call_policy():
    """Per call policy example.

    This example shows how to define your own policy and inject it with the "per_call_policies" parameter.
    """
    from azure.core.pipeline.policies import SansIOHTTPPolicy

    # Define your own policy
    class MyPolicy(SansIOHTTPPolicy[HttpRequest, HttpResponse]):
        def on_request(self, request: PipelineRequest[HttpRequest]) -> None:
            # Simple hook that redirect google calls to bing :).
            current_url = request.http_request.url
            request.http_request.url = current_url.replace("google", "bing")

    # Replace "PipelineClient" by your actual client (KeyVault, Storage, etc.)
    # "per_call_policies" is available on any client this team produces.
    client: PipelineClient[HttpRequest, HttpResponse] = PipelineClient(
        base_url="https://google.com", per_call_policies=MyPolicy()
    )
    # This part will be done by your client
    request = HttpRequest("GET", "https://google.com/")
    response: HttpResponse = client.send_request(request)

    # Checking that the response is coming from bing.
    assert "bing" in response.url