can az cli command automatically retry in case of http error 429 - azure

I have observed that az command prints http headers only if --debug flag is passed to it.
E.g.
az storage account list --debug
and headers are printed to stderr and stdout contains nothing.
In case of HTTP 429, too many errors errors, guidance is to retry after interval mentioned in Retry-After response header.
Is there any mechanism that can make az cli automatically retry the API in case of HTTP 429 error?
Edit -- Retries built into az command
urllib3.util.retry : Incremented Retry for (url='/subscriptions/REMOVED/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01'): Retry(total=3, connect=4, read=4, redirect=None, status=None)
urllib3.util.retry : Incremented Retry for (url='/subscriptions/REMOVED/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01'): Retry(total=2, connect=4, read=4, redirect=None, status=None)
urllib3.util.retry : Incremented Retry for (url='/subscriptions/REMOVED/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01'): Retry(total=1, connect=4, read=4, redirect=None, status=None)
urllib3.util.retry : Incremented Retry for (url='/subscriptions/REMOVED/providers/Microsoft.Storage/storageAccounts?api-version=2019-06-01'): Retry(total=0, connect=4, read=4, redirect=None, status=None)

Base on the responses received so far, answer is "No" and that caller must run az command with --debug option and parse stderr. Here is sample Groovy code.
def pat = /'Retry-After': '(\d+)'/
stderr.split("\n").each { line ->
def m = line =~ pat
if (m.size() > 0 && m.hasGroup()) {
retryAfterDuration = Integer.parseInt(m[0][1])
println("Found Retry-After header, value = ${retryAfterDuration}")
}
}
Here is sample response.
msrest.http_logger : Response status: 429
msrest.http_logger : Response headers:
msrest.http_logger : 'Cache-Control': 'no-cache'
msrest.http_logger : 'Pragma': 'no-cache'
msrest.http_logger : 'Content-Length': '207'
msrest.http_logger : 'Content-Type': 'application/json'
msrest.http_logger : 'Expires': '-1'
msrest.http_logger : 'Retry-After': '17'
msrest.http_logger : 'x-ms-request-id': 'c7102dca-4bb1-4d24-8333-0128b8b85b24'
msrest.http_logger : 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
msrest.http_logger : 'Server': 'Microsoft-Azure-Storage-Resource-Provider/1.0,Microsoft-HTTPAPI/2.0 Microsoft-HTTPAPI/2.0'
msrest.http_logger : 'x-ms-ratelimit-remaining-subscription-reads': '11989'
msrest.http_logger : 'x-ms-correlation-request-id': '3a7ba2e1-6908-414b-b162-d6f41dc10521'
msrest.http_logger : 'x-ms-routing-request-id': 'EASTUS:20200830T234133Z:3a7ba2e1-6908-414b-b162-d6f41dc10521'
msrest.http_logger : 'X-Content-Type-Options': 'nosniff'
msrest.http_logger : 'Date': 'Sun, 30 Aug 2020 23:41:32 GMT'
msrest.http_logger : 'Connection': 'close'
msrest.http_logger : Response content:
msrest.http_logger : {"error":{"code":"TooManyRequests","message":"The request is being throttled as the limit has been reached for operation type - List_PerHour. For more information, see - https://aka.ms/srpthrottlinglimits"}}
msrest.exceptions : The request is being throttled as the limit has been reached for operation type - List_PerHour. For more information, see - https://aka.ms/srpthrottlinglimits

Related

Cypress: intercept a network request with compression-type gzip to simulate mapbox

I am currently having trouble with mocking a particular request mapbox-gl is making. When the map is loaded from mapbox pbf-files are being requested and i have not been able to mock this.
My guess is that the core issue is that there seems to be an open bug with cypress issue-16420.
I tried alot of different intercept variants. I tried all kinds of response headers. I gziped, compressed, brd the file that I serve via fixture. I tried different encodings for the fixture. Nothing worked. One of the interceptors looks basically like this
cy.intercept({
method: 'GET',
url: '**/fonts/v1/mapbox/DIN%20Offc%20Pro%20Italic,Arial%20Unicode%20MS%20Regular/0-255.pbf?*',
}, {
fixture: 'fonts/italic.arial.0-255.pbf,binary',
statusCode: 204,
headers: {
'Connection': 'keep-alive',
'Keep-Alive': 'timeout=5',
'Transfer-Encoding': 'chunked',
'access-control-allow-origin': '*',
'access-control-expose-headers': 'Link',
'age': '11631145',
'cache-control': 'max-age=31536000',
'content-encoding': 'compress',
'content-type': 'application/x-protobuf',
'date': 'Sat, 19 Feb 2022 20:46:43 GMT',
'etag': 'W/"b040-+eCb/OHkPqToOcONTDlvpCrjmvs"',
'via': '1.1 4dd80d99fd5d0f6baaaf5179cd921f72.cloudfront.net (CloudFront)',
'x-amz-cf-id': '4uY9rjBgR_R12nkfHFrBMLEpNuWygW9DkmODlMEzwJHABTGCGg8pww==',
'x-amz-cf-pop': 'FRA56-P7',
'x-cache': 'Hit from cloudfront',
'x-origin': 'Mbx-Fonts'
}
}).as('get.0-255.pbf').as('getItalicArial0-255');
Now even if this is a bug there has to be some kind of workaround to serve the file in a cypress test without having an active internet connection. It would be great not having to rely on the network on tests. So all kinds of workarounds and dirty tricks are welcome in making this intercept work.

az cli creating deployment slot returning "unauthorised. develop"

I am a subscription owner,
I have an azure app service which is a web app for windows containers.
I can log in through the azure portal, and create a deployment slot through the UI without any issue.
However when I login through the azure cli, and try to use the following command to create a new deployment slot, I get a 403 error with a slightly odd message:
az webapp deployment slot create --name "foo-dev" --resource-group development --slot test --debug
I see it fail, with the following in the debug log output:
adal-python : XXXX - CacheDriver:Looking for potential cache entries: {'_clientId': '...', 'userId': '...'}
adal-python : XXXX - CacheDriver:Found 2 potential entries.
adal-python : XXXX - CacheDriver:Resource specific token found.
adal-python : dXXXX - CacheDriver:Returning token from cache lookup, AccessTokenId: b'XXXX ', RefreshTokenId: b'XXXX '
msrest.http_logger : Request URL: 'https://management.azure.com/subscriptions/XXXX/resourceGroups/development/providers/Microsoft.Web/sites/foo-dev/slots/test?api-version=2019-08-01'
msrest.http_logger : Request method: 'PUT'
msrest.http_logger : Request headers:
msrest.http_logger : 'Accept': 'application/json'
msrest.http_logger : 'Content-Type': 'application/json; charset=utf-8'
msrest.http_logger : 'accept-language': 'en-US'
msrest.http_logger : 'Content-Length': '368'
msrest.http_logger : 'User-Agent': 'python/3.6.6 (Windows-10-10.0.18362-SP0) msrest/0.6.13 msrest_azure/0.6.3 azure-mgmt-web/0.44.0 Azure-SDK-For-Python AZURECLI/2.4.0 (MSI)'
msrest.http_logger : Request body:
msrest.http_logger : {"location": "West Europe", "properties": {"serverFarmId": "/subscriptions/XXXX/resourceGroups/Development/providers/Microsoft.Web/serverfarms/foo-dev", "reserved": false, "isXenon": false, "hyperV": false, "siteConfig": {"netFrameworkVersion": "v4.6", "localMySqlEnabled": false, "http20Enabled": true}, "scmSiteAlsoStopped": false}}
msrest.universal_http : Configuring redirects: allow=True, max=30
msrest.universal_http : Configuring request: timeout=100, verify=True, cert=None
msrest.universal_http : Configuring proxies: ''
msrest.universal_http : Evaluate proxies against ENV settings: True
urllib3.connectionpool : https://management.azure.com:443 "PUT /subscriptions/XXXX/resourceGroups/development/providers/Microsoft.Web/sites/foo-dev/slots/test?api-version=2019-08-01 HTTP/1.1" 401 372
msrest.http_logger : Response status: 401
msrest.http_logger : Response headers:
msrest.http_logger : 'Cache-Control': 'no-cache'
msrest.http_logger : 'Pragma': 'no-cache'
msrest.http_logger : 'Content-Type': 'application/json; charset=utf-8'
msrest.http_logger : 'ETag': '"XXXX"'
msrest.http_logger : 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
msrest.http_logger : 'Server': 'Microsoft-IIS/10.0'
msrest.http_logger : 'X-AspNet-Version': '4.0.30319'
msrest.http_logger : 'X-Powered-By': 'ASP.NET'
msrest.http_logger : 'x-ms-ratelimit-remaining-subscription-resource-requests': '499'
msrest.http_logger : 'x-ms-request-id': 'XXXX'
msrest.http_logger : 'x-ms-correlation-request-id': 'f17fd4c0-51a0-4ae1-b869-396bf92e495f'
msrest.http_logger : 'x-ms-routing-request-id': 'UKSOUTH:20200422T082226Z:f17fd4c0-51a0-4ae1-b869-396bf92e495f'
msrest.http_logger : 'X-Content-Type-Options': 'nosniff'
msrest.http_logger : 'Date': 'Wed, 22 Apr 2020 08:22:26 GMT'
msrest.http_logger : 'Connection': 'close'
msrest.http_logger : Response content:
msrest.http_logger : {"Code":"Unauthorized","Message":"Access is denied. Not authorized. develop","Target":null,"Details":[{"Message":"Access is denied. Not authorized. develop"},{"Code":"Unauthorized"},{"ErrorEntity":{"ExtendedCode":"01001","MessageTemplate":"Access is denied.","Parameters":[],"Code":"Unauthorized","Message":"Access is denied. Not
authorized. develop"}}],"Innererror":null}
msrest.exceptions : Operation returned an invalid status code 'Unauthorized'
cli.azure.cli.core.util : Access is denied. Not authorized. develop
Access is denied. Not authorized. develop
az_command_data_logger : exit code: 1
telemetry.save : Save telemetry record of length 2540 in cache
I've replaced any sensitive values with XXXX in the output above.
This message seems odd to me: "Access is denied. Not authorized. develop"
Why the word "develop"? AFAIK that word doesn't relate to any of my named resources - i.e that doesn't correspond to the app name or the name of the resource group it's in (development) so it just seems odd to see that tacked on.. what does "develop" relate to here?
I can execute the list deployment slot command with the cli and that works fine.
UPDATE:
- The same error occurs in Azure Cloud Shell
- Yes the error is still happening (30th April 2020)
Please login in Azure portal and open Azure cloud Shell.
Run az account show command to confirm the account you logged in. If this account is your subscription owner, and the same error occurs, you need to raise a support ticket on Azure portal by following this link.

Making a batch API request to obtain several email bodies in MIME format

Outlook REST API provides an endpoint /me/messages/:message_id:/$value for requesting "raw" emails bodies (old good MIME-encoded email bodies). However, when I try to request bodies of several emails, using the Batch API (https://outlook.office.com/api/v2.0/$batch), I get only a single body in the response (the body of the first email in request I assume). The request body example:
--07edf27e-0552-45db-9a75-add15681b61b
Content-Type: application/http
MIME-Version: 1.0
Content-Transfer-Encoding: binary
GET /api/v2.0/me/messages/AAMkADllYjZhMmZhLWRiMWQtNGY5OS1hM2NiLTA3NDZmODA4NzZiMQBGAAAAAABdR0VqIHc_T6bmj6YLprUhBwDPSIJ3m0xMRZntj-YB8UfpAAAAAAEMAADPSIJ3m0xMRZntj-YB8UfpAAOHtNrzAAA=/$value HTTP/1.1
--07edf27e-0552-45db-9a75-add15681b61b
Content-Type: application/http
MIME-Version: 1.0
Content-Transfer-Encoding: binary
GET /api/v2.0/me/messages/AAMkADllYjZhMmZhLWRiMWQtNGY5OS1hM2NiLTA3NDZmODA4NzZiMQBGAAAAAABdR0VqIHc_T6bmj6YLprUhBwDPSIJ3m0xMRZntj-YB8UfpAAAAAAEMAADPSIJ3m0xMRZntj-YB8UfpAAOHtNryAAA=/$value HTTP/1.1
--07edf27e-0552-45db-9a75-add15681b61b
Content-Type: application/http
MIME-Version: 1.0
Content-Transfer-Encoding: binary
GET /api/v2.0/me/messages/AAMkADllYjZhMmZhLWRiMWQtNGY5OS1hM2NiLTA3NDZmODA4NzZiMQBGAAAAAABdR0VqIHc_T6bmj6YLprUhBwDPSIJ3m0xMRZntj-YB8UfpAAAAAAEMAADPSIJ3m0xMRZntj-YB8UfpAAOE7qpYAAA=/$value HTTP/1.1
--07edf27e-0552-45db-9a75-add15681b61b--
And response is of 'plain\text' Content-Type. Request/Response details:
{'Content-Length': '998', 'Accept-Encoding': 'gzip, deflate', 'Accept': u'application/json', 'User-Agent': u'Nimble', 'Connection': 'keep-alive', 'Content-Type': 'multipart/mixed; boundary="e91fd766-955d-4e87-9204-b28b004d3e5e"', 'Authorization': u'Bearer eyJ0eXAiOiJK..'}
ipdb> resp.request.url
'https://outlook.office.com/api/v2.0/me/$batch'
ipdb> resp.headers
{'X-CalculatedBETarget': 'VI1PR09MB2479.eurprd09.prod.outlook.com', 'Rate-Limit-Reset': '2020-02-06T18:49:26.260Z', 'X-Powered-By': 'ASP.NET', 'Transfer-Encoding': 'chunked', 'X-RUM-Validated': '1', 'X-BackEndHttpStatus': '200, 200', 'X-Proxy-RoutingCorrectness': '1', 'X-BeSku': 'WCS5', 'Date': 'Thu, 06 Feb 2020 18:39:10 GMT', 'Rate-Limit-Limit': '10000', 'Rate-Limit-Remaining': '9999', 'X-AspNet-Version': '4.0.30319', 'Server': 'Microsoft-IIS/10.0', 'X-BEServer': 'VI1PR09MB2479', 'X-DiagInfo': 'VI1PR09MB2479', 'X-FEServer': 'VI1PR0502CA0025, MWHPR10CA0071', 'X-MailboxGuid': '9eb6a2fa-db1d-4f99-a3cb-0746f80876b1', 'X-FEProxyInfo': 'VI1PR0502CA0025.EURPRD05.PROD.OUTLOOK.COM', 'x-ms-appId': 'b27e9f81-dbc4-4d4a-923a-3eacaae45241', 'request-id': 'ff7b1bce-5d41-450f-800a-d2de6f9ae2f0', 'X-Proxy-BackendServerStatus': '200', 'X-CalculatedFETarget': 'VI1PR0502CU001.internal.outlook.com', 'Cache-Control': 'private', **'Content-Type': 'text/plain'**}
If performing the same request but without requesting "raw" bodies, the response becomes of expected content-type: 'Content-Type': 'multipart/mixed; boundary=batchresponse_e4ca25bf-f9e7-4d69-bc09-139bf2776db0'. The request body:
--006b59ee-e662-46d8-be97-a21a24cc9b08
Content-Type: application/http
MIME-Version: 1.0
Content-Transfer-Encoding: binary
GET /api/v2.0/me/messages/AAMkADllYjZhMmZhLWRiMWQtNGY5OS1hM2NiLTA3NDZmODA4NzZiMQBGAAAAAABdR0VqIHc_T6bmj6YLprUhBwDPSIJ3m0xMRZntj-YB8UfpAAAAAAEMAADPSIJ3m0xMRZntj-YB8UfpAAOHtNrzAAA= HTTP/1.1
--006b59ee-e662-46d8-be97-a21a24cc9b08
Content-Type: application/http
MIME-Version: 1.0
Content-Transfer-Encoding: binary
GET /api/v2.0/me/messages/AAMkADllYjZhMmZhLWRiMWQtNGY5OS1hM2NiLTA3NDZmODA4NzZiMQBGAAAAAABdR0VqIHc_T6bmj6YLprUhBwDPSIJ3m0xMRZntj-YB8UfpAAAAAAEMAADPSIJ3m0xMRZntj-YB8UfpAAOHtNryAAA= HTTP/1.1
--006b59ee-e662-46d8-be97-a21a24cc9b08
Content-Type: application/http
MIME-Version: 1.0
Content-Transfer-Encoding: binary
GET /api/v2.0/me/messages/AAMkADllYjZhMmZhLWRiMWQtNGY5OS1hM2NiLTA3NDZmODA4NzZiMQBGAAAAAABdR0VqIHc_T6bmj6YLprUhBwDPSIJ3m0xMRZntj-YB8UfpAAAAAAEMAADPSIJ3m0xMRZntj-YB8UfpAAOE7qpYAAA= HTTP/1.1
--006b59ee-e662-46d8-be97-a21a24cc9b08--
ipdb> resp.headers
{'X-CalculatedBETarget': 'VI1PR09MB2479.eurprd09.prod.outlook.com', 'Rate-Limit-Reset': '2020-02-06T18:49:26.260Z', 'X-Powered-By': 'ASP.NET', 'Transfer-Encoding': 'chunked', 'X-RUM-Validated': '1', 'OData-Version': '4.0', 'X-BackEndHttpStatus': '200, 200', 'X-Proxy-RoutingCorrectness': '1', 'X-BeSku': 'WCS5', 'Date': 'Thu, 06 Feb 2020 18:45:54 GMT', 'Rate-Limit-Limit': '10000', 'Rate-Limit-Remaining': '9984', 'X-AspNet-Version': '4.0.30319', 'Server': 'Microsoft-IIS/10.0', 'X-BEServer': 'VI1PR09MB2479', 'X-DiagInfo': 'VI1PR09MB2479', 'X-FEServer': 'VI1PR03CA0059, MWHPR04CA0069', 'X-MailboxGuid': '9eb6a2fa-db1d-4f99-a3cb-0746f80876b1', 'X-FEProxyInfo': 'VI1PR03CA0059.EURPRD03.PROD.OUTLOOK.COM', 'x-ms-appId': 'b27e9f81-dbc4-4d4a-923a-3eacaae45241', 'request-id': '7f5dcc0f-4109-48a1-9948-39a5ad7471e6', 'X-Proxy-BackendServerStatus': '200', 'X-CalculatedFETarget': 'VI1PR03CU002.internal.outlook.com', 'Cache-Control': 'private', 'Content-Type': 'multipart/mixed; boundary=batchresponse_e4ca25bf-f9e7-4d69-bc09-139bf2776db0'}
ipdb> resp.request.url
'https://outlook.office.com/api/v2.0/me/$batch'
Is it a bug in Outlook REST API? The same request, but to the Graph API works correctly (unfortunately we can't use the Graph API in production).

Error 403 while using exchangelib to access Outlook Exchange server to read emails

I'm trying to read emails from the Microsoft Exchange server using EWS and exchangelib in Python for an email classification problem. But I am unable to connect to the exchange server.
I've tried specifying the version, auth_type, using a certificate (which gives a ssl verify error), using the smtp address in place of the username and it still doesn't connect.
Here is my code:
from exchangelib import Credentials, Account, EWSDateTime, EWSTimeZone, Configuration, DELEGATE, IMPERSONATION, NTLM, ServiceAccount, Version, Build
USER_NAME = 'domain\\user12345'
ACCOUNT_EMAIL = john.doe#ext.companyname.com'
ACCOUNT_PASSWORD = 'John#1234'
ACCOUNT_SERVER = 'oa.company.com'
creds = Credentials(USER_NAME, ACCOUNT_PASSWORD)
config = Configuration(server=ACCOUNT_SERVER, credentials=creds)
account = Account(primary_smtp_address=ACCOUNT_EMAIL, config=config, autodiscover=False, access_type=DELEGATE)
print('connecting ms exchange server account...')
print(type(account))
print(dir(account))
account.root.refresh()
Here is the error I am getting:
TransportError: Unknown failure
Retry: 0
Waited: 10
Timeout: 120
Session: 26271
Thread: 15248
Auth type: <requests_ntlm.requests_ntlm.HttpNtlmAuth object at 0x00000259AA1BD588>
URL: https://oa.company.com/EWS/Exchange.asmx
HTTP adapter: <requests.adapters.HTTPAdapter object at 0x00000259AA0DB7B8>
Allow redirects: False
Streaming: False
Response time: 0.28100000000085856
Status code: 403
Request headers: {'User-Agent': 'python-requests/2.21.0', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'Keep-Alive', 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': '469', 'Authorization': 'NTLM TlRMTVNTUAADAAAAGAAYAG0AAAAOAQ4BhQAAAAwADABYAAAACQAJAGQAAAAAAAAAbQAAABAAEACTAQAANoKJ4gYBsR0AAAAP7Pyb+wBnMdrlhr4FKVqPbklDSUNJQkFOS0xURElQUlUzODE5MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJTLmMBLPHowOJZ46XDs+4ABAQAAAAAAAAZdRefQLNUB+Fc6Z26oxvgAAAAAAgAYAEkAQwBJAEMASQBCAEEATgBLAEwAVABEAAEAEgBIAFkARABFAFgAQwBIADAAOAAEACAAaQBjAGkAYwBpAGIAYQBuAGsAbAB0AGQALgBjAG8AbQADADQASABZAEQARQBYAEMASAAwADgALgBpAGMAaQBjAGkAYgBhAG4AawBsAHQAZAAuAGMAbwBtAAUAIABpAGMAaQBjAGkAYgBhAG4AawBsAHQAZAAuAGMAbwBtAAcACAAGXUXn0CzVAQYABAACAAAACgAQAD9EWlwiiUs304wucsxnkyQAAAAAAAAAALfelDwG05hYOMUqY/e60PY=', 'Cookie': 'ClientId=SINZWMOJKWSKDGEKASFG; expires=Fri, 26-Jun-2020 10:13:02 GMT; path=/; HttpOnly'}
Response headers: {'Cache-Control': 'private', 'Server': 'Microsoft-IIS/8.5', 'request-id': 'ae4dee8d-34e0-471c-8252-b8c1056c8ea0', 'X-CalculatedBETarget': 'pqrexch05.domain.com', 'X-DiagInfo': 'PQREXCH05', 'X-BEServer': 'PQREXCH05', 'X-AspNet-Version': '4.0.30319', 'Set-Cookie': 'exchangecookie=681afc8a0905459182363cce9a98d021; expires=Sat, 27-Jun-2020 10:13:02 GMT; path=/; HttpOnly, X-BackEndCookie=S-1-5-21-1343024091-725345543-504838010-1766210=u56Lnp2ejJqBy87Iysqem5nSy8mbnNLLyZ7H0sfIysbSy5vMz8qdzcvPnpzHgYHNz87G0s/I0s3Iq87Pxc7Mxc/N; expires=Sat, 27-Jul-2019 10:13:02 GMT; path=/EWS; secure; HttpOnly', 'Persistent-Auth': 'true', 'X-Powered-By': 'ASP.NET', 'X-FEServer': 'PQREXCH05', 'Date': 'Thu, 27 Jun 2019 10:13:01 GMT', 'Content-Length': '0'}
Request data: b'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<s:Envelope xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"><s:Header><t:RequestServerVersion Version="Exchange2013_SP1"/></s:Header><s:Body><m:ResolveNames ReturnFullContactData="false"><m:UnresolvedEntry>ICICIBANKLTD\\IPRU38190</m:UnresolvedEntry></m:ResolveNames></s:Body></s:Envelope>'
Response data: b''
You might need to configure access policy for EWS using PowerShell.
For example (to allow all apps to use REST and EWS):
Set-OrganizationConfig -EwsApplicationAccessPolicy EnforceBlockList -EwsBlockList $null
Taken from Microsoft docs on Set-OrganizationConfig.
Please search for EwsApplicationAccessPolicy in the above link for more granular access control examples.

Request email audit export fails with status 400 and "Premature end of file."

according to https://developers.google.com/admin-sdk/email-audit/#creating_a_mailbox_for_export I am trying to request the email audit export of an user in G Suite this way:
def requestAuditExport(account):
credentials = getCredentials()
http = credentials.authorize(httplib2.Http())
url = 'https://apps-apis.google.com/a/feeds/compliance/audit/mail/export/helpling.com/'+account
status, response = http.request(url, 'POST', headers={'Content-Type': 'application/atom+xml'})
print(status)
print(response)
And I get the following result:
{'content-length': '22', 'expires': 'Tue, 13 Dec 2016 14:19:37 GMT', 'date': 'Tue, 13 Dec 2016 14:19:37 GMT', 'x-frame-options': 'SAMEORIGIN', 'transfer-encoding': 'chunked', 'x-xss-protection': '1; mode=block', 'content-type': 'text/html; charset=UTF-8', 'x-content-type-options': 'nosniff', '-content-encoding': 'gzip', 'server': 'GSE', 'status': '400', 'cache-control': 'private, max-age=0', 'alt-svc': 'quic=":443"; ma=2592000; v="35,34"'}
b'Premature end of file.'
I cannot see where the problem is, can someone please give me a hint?
Thanks in advance!
Kay
Fix it by going intp the Admin Console, Manage API client access page under Security and add the Client ID, scope needed for the Directory API. For more information, check this document.
Okay, found out what was wrong and fixed it myself. Finally it looks like this:
http = getCredentials().authorize(httplib2.Http())
url = 'https://apps-apis.google.com/a/feeds/compliance/audit/mail/export/helpling.com/'+account
headers = {'Content-Type': 'application/atom+xml'}
xml_data = """<atom:entry xmlns:atom='http://www.w3.org/2005/Atom' xmlns:apps='http://schemas.google.com/apps/2006'> \
<apps:property name='includeDeleted' value='true'/> \
</atom:entry>"""
status, response = http.request(url, 'POST', headers=headers, body=xml_data)
Not sure if it was about the body or the header. It works now and I hope it will help others.
Thanks anyway.

Resources