-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfunction_app.py
223 lines (187 loc) · 9.11 KB
/
function_app.py
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import json
import azure.functions as func
import datetime
import logging
app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
@app.function_name(name="timertest")
@app.schedule(schedule="*/10 * * * * *", arg_name="dummy", run_on_startup=False,
use_monitor=False) # Timer Trigger
def timer_function(dummy: func.TimerRequest) -> None:
utc_timestamp = datetime.datetime.utcnow().replace(
tzinfo=datetime.timezone.utc).isoformat()
if dummy.past_due:
logging.info('The timer is past due!')
logging.info('Python timer trigger function ran at %s', utc_timestamp)
@app.event_hub_message_trigger(arg_name="myhub", event_hub_name="inputhub",
connection="EHConnectionString") # Eventhub trigger
@app.event_hub_output(arg_name="outputhub", event_hub_name="outputhub",
connection="EHConnectionString") # Eventhub output binding
def event_hub_message_trigger(myhub: func.EventHubEvent, outputhub: func.Out[str]):
outputhub.set("hello")
@app.queue_trigger(arg_name="msg", queue_name="inputqueue",
connection="storageAccountConnectionString") # Queue trigger
@app.queue_output(arg_name="outputQueueItem", queue_name="outqueue",
connection="storageAccountConnectionString") # Queue output binding
def queue_trigger(msg: func.QueueMessage,
outputQueueItem: func.Out[str]) -> None:
logging.info('Python queue trigger function processed a queue item: %s',
msg.get_body().decode('utf-8'))
outputQueueItem.set('hello')
@app.service_bus_topic_trigger(arg_name="serbustopictrigger",
topic_name="inputtopic",
connection="topicConnectionString",
subscription_name="testsub") # service bus topic trigger
@app.service_bus_topic_output(arg_name="serbustopicbinding",
connection="outputtopicConnectionString",
topic_name="outputtopic",
subscription_name="testsub") # service bus topic output binding
def service_bus_topic_trigger(serbustopictrigger: func.ServiceBusMessage,
serbustopicbinding: func.Out[str]) -> None:
logging.info('Python ServiceBus queue trigger processed message.')
result = json.dumps({
'message_id': serbustopictrigger.message_id,
'body': serbustopictrigger.get_body().decode('utf-8'),
'content_type': serbustopictrigger.content_type,
'expiration_time': serbustopictrigger.expiration_time,
'label': serbustopictrigger.label,
'partition_key': serbustopictrigger.partition_key,
'reply_to': serbustopictrigger.reply_to,
'reply_to_session_id': serbustopictrigger.reply_to_session_id,
'scheduled_enqueue_time': serbustopictrigger.scheduled_enqueue_time,
'session_id': serbustopictrigger.session_id,
'time_to_live': serbustopictrigger.time_to_live
}, default=str)
logging.info(result)
serbustopicbinding.set("topic works!!")
@app.service_bus_queue_trigger(arg_name="serbustopictrigger",
queue_name="inputqueue",
connection="queueConnectionString") # service bus queue trigger
@app.service_bus_queue_output(arg_name="serbustopicbinding",
connection="queueConnectionString",
queue_name="outputqueue") # service bus queue output binding
def service_bus_queue_trigger(serbustopictrigger: func.ServiceBusMessage,
serbustopicbinding: func.Out[str]) -> None:
logging.info('Python ServiceBus queue trigger processed message.')
result = json.dumps({
'message_id': serbustopictrigger.message_id,
'body': serbustopictrigger.get_body().decode('utf-8'),
'content_type': serbustopictrigger.content_type,
'expiration_time': serbustopictrigger.expiration_time,
'label': serbustopictrigger.label,
'partition_key': serbustopictrigger.partition_key,
'reply_to': serbustopictrigger.reply_to,
'reply_to_session_id': serbustopictrigger.reply_to_session_id,
'scheduled_enqueue_time': serbustopictrigger.scheduled_enqueue_time,
'session_id': serbustopictrigger.session_id,
'time_to_live': serbustopictrigger.time_to_live
}, default=str)
logging.info(result)
serbustopicbinding.set("queue works!!")
@app.cosmos_db_trigger(arg_name="triggerDocs", database_name="billdb",
collection_name="billcollection",
connection_string_setting="CosmosDBConnectionString",
lease_collection_name="leasesstuff",
create_lease_collection_if_not_exists="true") # Cosmos DB Trigger
@app.cosmos_db_output(arg_name="outDoc", database_name="billdb",
collection_name="outColl",
connection_string_setting="CosmosDBConnectionString") # Cosmos DB input binding
@app.cosmos_db_input(arg_name="inDocs", database_name="billdb",
collection_name="incoll",
connection_string_setting="CosmosDBConnectionString") # Cosmos DB output binding
def cosmos_db_trigger(triggerDocs: func.DocumentList, inDocs: func.DocumentList,
outDoc: func.Out[func.Document]) -> str:
if triggerDocs:
triggerDoc = triggerDocs[0]
logging.info(inDocs[0]['text'])
triggerDoc['ssss'] = 'Hello updated2!'
outDoc.set(triggerDoc)
@app.blob_trigger(arg_name="triggerBlob", path="input-container/{name}",
connection="AzureWebJobsStorage")
@app.blob_output(arg_name="outputBlob", path="output-container/{name}",
connection="AzureWebJobsStorage")
@app.blob_input(arg_name="readBlob", path="output-container/{name}",
connection="AzureWebJobsStorage")
def blob_trigger(triggerBlob: func.InputStream, readBlob: func.InputStream,
outputBlob: func.Out[str]) -> None:
logging.info(f"Blob trigger executed!")
logging.info(f"Blob Name: {triggerBlob.name} ({triggerBlob.length}) bytes")
logging.info(f"Full Blob URI: {triggerBlob.uri}")
outputBlob.set('hello')
logging.info(f"Output blob: {readBlob.read()}")
@app.event_grid_trigger(arg_name="eventGridEvent")
@app.event_grid_output(
arg_name="outputEvent",
topic_endpoint_uri="MyEventGridTopicUriSetting",
topic_key_setting="MyEventGridTopicKeySetting")
def event_grid_trigger(eventGridEvent: func.EventGridEvent,
outputEvent: func.Out[func.EventGridOutputEvent]) -> None:
logging.info("eventGridEvent: ", eventGridEvent)
outputEvent.set(
func.EventGridOutputEvent(
id="test-id",
data={"tag1": "value1", "tag2": "value2"},
subject="test-subject",
event_type="test-event-1",
event_time=datetime.datetime.utcnow(),
data_version="1.0"))
# To run wsgi app using new prog model python function, please uncomment below section and comment out rest of file
# from flask import Flask, make_response, request
# flask_app = Flask(__name__)
# @flask_app.route("/")
# def index():
# return (
# "Try /hello/Chris for parameterized Flask route.\n"
# "Try /module for module import guidance"
# )
# @flask_app.route("/hello/<name>", methods=['GET','POST','DELETE'])
# def hello(name: str):
# return f"hello {name}"
# app = func.FunctionApp(wsgi_app=flask_app.wsgi_app, auth_level=func.AuthLevel.ANONYMOUS)
# To run asgi app using new prog model python function, please uncomment below section and comment out rest of file
# import fastapi
# import json
# import mimesis
# from pydantic import BaseModel
# fast_app = fastapi.FastAPI()
# @fast_app.get("/hello")
# async def get_food(
# name: str
# ):
# return f"hello {name}"
# class FoodItem(BaseModel):
# id: int
# vegetable: str
# dish: str
# drink: str
# @fast_app.get("/hello")
# async def get_food(
# name: str
# ):
# return f"hello {name}"
# @fast_app.get("/food/{food_id}")
# async def get_food(
# food_id: int,
# ):
# food = mimesis.Food()
# return {
# "food_id": food_id,
# "vegetable": food.vegetable(),
# "dish": food.dish(),
# "drink": food.drink(),
# }
# @fast_app.post("/food/")
# async def create_food(food: FoodItem):
# # Write the food item to the database here.
# return food
# @fast_app.get("/users/{user_id}")
# async def read_item(user_id: int, locale: Optional[str] = None):
# fake_user = mimesis.Person(locale=locale)
# return {
# "user_id": user_id,
# "username": fake_user.username(),
# "fullname": fake_user.full_name(),
# "age": fake_user.age(),
# "firstname": fake_user.first_name(),
# "lastname": fake_user.last_name(),
# }
# app = func.FunctionApp(asgi_app=fast_app, auth_level=func.AuthLevel.ANONYMOUS)