-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathAzureQueue.py
More file actions
157 lines (119 loc) · 6.88 KB
/
AzureQueue.py
File metadata and controls
157 lines (119 loc) · 6.88 KB
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
"""
A simple, lightweight library for communicating with the Azure Queue Storage REST API.
Author Tim Hanewich, github.com/TimHanewich
Find updates to this code: https://github.com/TimHanewich/MicroPython-Collection/tree/master/AzureQueue
MIT License
Copyright 2024 Tim Hanewich
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 requests
def urljoin(part1:str, part2:str) -> str:
"""Combines two portions into a single URL, being mindful of repeating slashes."""
if len(part1) == 0:
return part2
elif len(part2) == 0:
return part1
# strip out trailing
if part1[len(part1) - 1] == "/":
part1 = part1[:-1]
# strip out leading
if part2[0] == "/":
part2 = part2[1:]
return part1 + "/" + part2
def get_xml_tag(body:str, tag_name:str) -> str:
"""Strips out a value from the body based on the XML tag name it resides in."""
try:
i1:int = body.index("<" + tag_name + ">")
i1:int = body.index(">", i1 + 1)
i2:int = body.index("<", i1 + 1)
return body[i1+1:i2]
except:
raise Exception("Unable to find XML tag '" + tag_name + "' in provided body.")
class QueueMessage:
def __init__(self):
self._id:str = None
self._pop:str = None
self._txt:str = None
@property
def MessageId(self) -> str:
return self._id
@MessageId.setter
def MessageId(self, value) -> None:
self._id = value
@property
def PopReceipt(self) -> str:
return self._pop
@PopReceipt.setter
def PopReceipt(self, value) -> None:
self._pop = value
@property
def MessageText(self) -> str:
return self._txt
@MessageText.setter
def MessageText(self, value) -> None:
self._txt = value
def __repr__(self):
return str({"MessageId": self.MessageId, "PopReceipt": self.PopReceipt, "MessageText": self.MessageText})
class QueueService:
"""Brokers communication with the Azure Queue REST API"""
def __init__(self, queue_url:str, sas_token:str):
"""
Creates a new instance of the QueueService class, ready to communicate with a specific queue within a specific Azure Storage Account.
Parameters:
queue_url (str): The URL directly to the Azure Storage Queue, i.e. "https://mystorageaccount.queue.core.windows.net/myqueue"
sas_token (str): The Shared Access Signature (SAS) you get when generating in the Azure Portal. i.e. "sv=2022-11-02&ss=bfqt&srt=c&sp=rwdlacupiytfx&se=2024-11-30T19:34:10Z&st=2024-11-30T11:34:10Z&spr=https&sig=%2FKxtw%2FTzD0lXqj2kGyMuJ9Y0cFb16javsQb7Pz4b6KM%3D"
"""
# ensure the URL has an actual queue name in it
if "/" not in queue_url.lower().replace("https://", "").replace("http://", "") or queue_url[len(queue_url) - 1] == "/":
raise Exception("You did not provide the URL to a specific Queue in the URL you provided. Ensure the URL you are providing is not only to a specific storage account, but also to a specific queue (i.e. '/myqueue' at the end)!")
self._url = queue_url
self._token = sas_token
def put(self, text:str) -> None:
"""Adds a new message to the queue."""
# construct body
body:str = "<QueueMessage><MessageText>" + text + "</MessageText></QueueMessage>"
# Make POST request
post_url:str = urljoin(self._url, "messages") + "?" + self._token
headers = {"Content-Type": "application/xml"}
response = requests.post(post_url, headers=headers, data=body)
# handle code?
if response.status_code != 201:
raise Exception("POST request to Azure Queue Service to upload message returned status code '" + str(response.status_code) + "', not the successful '201 CREATED'!")
def receive(self) -> QueueMessage:
"""Receives the next message from the queue, but does NOT delete it."""
# make get request
get_url:str = urljoin(self._url, "messages") + "?" + self._token
response = requests.get(get_url)
response_body:str = response.text
# handle error
if response.status_code != 200:
raise Exception("GET request to receive queue message returned status code " + str(response.status_code) + "! Body: " + response_body)
# if there was no queue messages left
if "<QueueMessagesList />" in response_body: # an empty list
return None
# get data from response body
ToReturn:QueueMessage = QueueMessage()
ToReturn.MessageId = get_xml_tag(response_body, "MessageId")
ToReturn.PopReceipt = get_xml_tag(response_body, "PopReceipt")
ToReturn.MessageText = get_xml_tag(response_body, "MessageText")
return ToReturn
def delete(self, message_id:str, pop_receipt:str) -> None:
"""Deletes a message from the queue."""
# make DELETE request
delete_url:str = urljoin(urljoin(self._url, "messages"), message_id) + "?popreceipt=" + pop_receipt.replace("+", "%2B") + "&" + self._token
response = requests.delete(delete_url)
# handle error
if response.status_code != 204: # when successful, it returns 204 NO CONTENT
response_body:str = response.text
raise Exception("Deletion of message '" + message_id + "' was unsuccessful! Status code '" + str(response.status_code) + "' was returned. Body: " + response_body)
def clear(self) -> None:
"""Clears the queue of all messages"""
# make DELETE request
delete_url:str = urljoin(self._url, "messages") + "?" + self._token
response = requests.delete(delete_url)
# handle error
if response.status_code != 204: # when successful, it returns 204 NO CONTENT
response_body:str = response.text
raise Exception("Clearing of queue was unsuccessful! Status code '" + str(response.status_code) + "' was returned. Body: " + response_body)