-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
66 lines (55 loc) · 2.47 KB
/
app.py
File metadata and controls
66 lines (55 loc) · 2.47 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
import base64
from io import BytesIO
from PIL import Image
from azure.servicebus import ServiceBusMessage, ServiceBusClient, ServiceBusReceiveMode
from flask import Flask, render_template, request, redirect, make_response
app = Flask(__name__)
app_queue = "appqueue"
web_queue = "webqueue"
connection_str = "Endpoint=sb://lab204servicebus575.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=f/YBYnUfXCwRR8pOfFXHnKcm0O4CMkCmpbXke7/TTqc="
@app.route('/')
def home():
return render_template('home.html')
@app.route('/', methods=['POST'])
def upload_image():
if 'file' not in request.files:
print('No file part')
return redirect(request.url)
file = request.files['file']
print(file.filename)
img = Image.open(file.stream)
buffered = BytesIO()
img.save(buffered, format="JPEG")
img_str = base64.b64encode(buffered.getvalue()).decode()
message = ServiceBusMessage(body=img_str, content_type="text/plain")
print(str(message.body))
servicebus_client = ServiceBusClient.from_connection_string(conn_str=connection_str, logging_enable=True)
with servicebus_client:
# get a Queue Sender object to send messages to the queue
sender = servicebus_client.get_queue_sender(queue_name=app_queue)
with sender:
sender.send_messages(message)
print(f"Message published to topic: {app_queue}")
return redirect(request.url)
@app.route('/view', methods=['GET'])
def retrieve_img():
res = {}
servicebus_client = ServiceBusClient.from_connection_string(conn_str=connection_str, logging_enable=True)
with servicebus_client:
# get the Queue Receiver object for the queue
receiver = servicebus_client.get_queue_receiver(queue_name=web_queue, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK)
msgs = receiver.receive_messages(max_message_count=1)
if len(msgs) == 1:
msg = msgs[0]
print(f"Received: {msg.body}.")
res["dec_str"] = str(msg)
receiver.complete_message(message=msg)
if len(res) < 1:
return "fail", 400
else:
response = make_response(res["dec_str"])
response.headers.set('Content-Type', 'image/gif')
response.headers.set('Content-Disposition', 'attachment', filename='image.gif')
return response
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)