Skip to content

Commit d996f13

Browse files
Misc fixes for Python (#1085)
1 parent 457e65c commit d996f13

File tree

11 files changed

+58
-26
lines changed

11 files changed

+58
-26
lines changed

Python/alerts-to-discord/main.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ def post_fatal_issue_to_discord(
8282
try:
8383
# [START v2SendToDiscord]
8484
response = post_message_to_discord(
85-
"Crashlytics Bot", message, DISCORD_WEBHOOK_URL.value()
85+
"Crashlytics Bot", message, DISCORD_WEBHOOK_URL.value
8686
)
8787
if response.ok:
8888
print(
@@ -115,14 +115,14 @@ def post_new_udid_to_discord(
115115
message = f"""
116116
📱 New iOS device registered by {app_dist.tester_name} <{app_dist.tester_email}> for {app_id}
117117
118-
UDID **{app_dist.device_id}** for {app_dist.device_model}
118+
UDID **{app_dist.tester_device_identifier}** for {app_dist.tester_device_model_name}
119119
""".strip()
120120
# [END v2AppDistributionEventPayload]
121121

122122
try:
123123
# [START v2SendNewTesterIosDeviceToDiscord]
124124
response = post_message_to_discord(
125-
"App Distro Bot", message, DISCORD_WEBHOOK_URL.value()
125+
"App Distro Bot", message, DISCORD_WEBHOOK_URL.value
126126
)
127127
if response.ok:
128128
print(
@@ -168,7 +168,7 @@ def post_performance_alert_to_discord(
168168
try:
169169
# [START v2SendPerformanceAlertToDiscord]
170170
response = post_message_to_discord(
171-
"App Performance Bot", message, DISCORD_WEBHOOK_URL.value()
171+
"App Performance Bot", message, DISCORD_WEBHOOK_URL.value
172172
)
173173
if response.ok:
174174
print(

Python/delete-unused-accounts-cron/main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,10 @@
3030
# [START accountcleanup]
3131
# Run once a day at midnight, to clean up inactive users.
3232
# Manually run the task here https://console.cloud.google.com/cloudscheduler
33-
@scheduler_fn.on_schedule("every day 00:00")
33+
@scheduler_fn.on_schedule(schedule="every day 00:00")
3434
def accountcleanup(event: scheduler_fn.ScheduledEvent) -> None:
3535
"""Delete users who've been inactive for 30 days or more."""
36-
user_page: auth.ListUsersPage = auth.list_users()
36+
user_page: auth.ListUsersPage | None = auth.list_users()
3737
while user_page is not None:
3838
inactive_uids = [
3939
user.uid

Python/post-signup-event/main.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def savegoogletoken(
5959

6060
tasks_client = google.cloud.tasks_v2.CloudTasksClient()
6161
task_queue = tasks_client.queue_path(
62-
params.PROJECT_ID.value(),
62+
params.PROJECT_ID.value,
6363
options.SupportedRegion.US_CENTRAL1,
6464
"scheduleonboarding",
6565
)
@@ -105,7 +105,10 @@ def scheduleonboarding(request: tasks_fn.CallableRequest) -> https_fn.Response:
105105
user_info = (
106106
firestore_client.collection("user_info").document(uid).get().to_dict()
107107
)
108-
if "calendar_access_token" not in user_info:
108+
if (
109+
not isinstance(user_info, dict)
110+
or "calendar_access_token" not in user_info
111+
):
109112
return https_fn.Response(
110113
status=https_fn.FunctionsErrorCode.PERMISSION_DENIED,
111114
response="No Google OAuth token found.",
@@ -145,6 +148,8 @@ def scheduleonboarding(request: tasks_fn.CallableRequest) -> https_fn.Response:
145148
calendarId="primary", body=calendar_event
146149
).execute()
147150

151+
return https_fn.Response("Success")
152+
148153

149154
# [END scheduleonboarding]
150155

Python/quickstarts/auth-blocking-functions/main.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ def sendverification(
111111
event: identity_fn.AuthBlockingEvent,
112112
) -> identity_fn.BeforeCreateResponse | None:
113113
if event.data.email is not None and not event.data.email_verified:
114-
link = auth.generate_email_verification_link()
114+
link = auth.generate_email_verification_link(event.data.email)
115115
send_verification_email_using_your_smtp_server(event.data.email, link)
116116

117117

@@ -171,6 +171,7 @@ def setemployeeid(
171171
) -> identity_fn.BeforeCreateResponse | None:
172172
if (
173173
event.credential is not None
174+
and event.credential.claims is not None
174175
and event.credential.provider_id == "saml.my-provider-id"
175176
):
176177
return identity_fn.BeforeCreateResponse(
@@ -184,6 +185,7 @@ def copyclaimstosession(
184185
) -> identity_fn.BeforeSignInResponse | None:
185186
if (
186187
event.credential is not None
188+
and event.credential.claims is not None
187189
and event.credential.provider_id == "saml.my-provider-id"
188190
):
189191
return identity_fn.BeforeSignInResponse(

Python/quickstarts/callable-functions/main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def addmessage(req: https_fn.CallableRequest) -> Any:
116116
# Saving the new message to the Realtime Database.
117117
sanitized_message = sanitize_text(text) # Sanitize message.
118118
db.reference("/messages").push(
119-
{
119+
{ # type: ignore
120120
"text": sanitized_message,
121121
"author": {
122122
"uid": uid,
@@ -135,7 +135,7 @@ def addmessage(req: https_fn.CallableRequest) -> Any:
135135
# Re-throwing the error as an HttpsError so that the client gets
136136
# the error details.
137137
raise https_fn.HttpsError(
138-
code=https_fn.FunctionsErrorCode.UNKNOWN, message=e, details=e
138+
code=https_fn.FunctionsErrorCode.UNKNOWN, message="Error", details=e
139139
)
140140

141141

Python/quickstarts/custom-events/main.py

+8
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
def onimageresized(event: eventarc_fn.CloudEvent) -> None:
3131
print("Received image resize completed event: ", event.type)
3232

33+
if not isinstance(event.subject, str):
34+
print("No 'subject' data.")
35+
return
36+
3337
# For example, write resized image details into Firestore.
3438
firestore_client: google.cloud.firestore.Client = firestore.client()
3539
collection = firestore_client.collection("images")
@@ -51,6 +55,10 @@ def onimageresized(event: eventarc_fn.CloudEvent) -> None:
5155
def onimageresizedwest(event: eventarc_fn.CloudEvent) -> None:
5256
print("Received image resize completed event: ", event.type)
5357
# [START_EXCLUDE]
58+
if not isinstance(event.subject, str):
59+
print("No 'subject' data.")
60+
return
61+
5462
# For example, write resized image details into Firestore.
5563
firestore_client: google.cloud.firestore.Client = firestore.client()
5664
collection = firestore_client.collection("images")

Python/quickstarts/pubsub-helloworld/main.py

+2
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@ def hellopubsubjson(
5252
except ValueError:
5353
print("PubSub message was not JSON")
5454
return
55+
if data is None:
56+
return
5557
if "name" not in data:
5658
print("No 'name' key")
5759
return

Python/quickstarts/uppercase-firestore/main.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -56,13 +56,15 @@ def addmessage(req: https_fn.Request) -> https_fn.Response:
5656
# [START makeUppercase]
5757
@firestore_fn.on_document_created(document="messages/{pushId}")
5858
def makeuppercase(
59-
event: firestore_fn.Event[firestore_fn.DocumentSnapshot],
59+
event: firestore_fn.Event[firestore_fn.DocumentSnapshot | None],
6060
) -> None:
6161
"""Listens for new documents to be added to /messages. If the document has
6262
an "original" field, creates an "uppercase" field containg the contents of
6363
"original" in upper case."""
6464

6565
# Get the value of "original" if it exists.
66+
if event.data is None:
67+
return
6668
try:
6769
original = event.data.get("original")
6870
except KeyError:

Python/quickstarts/uppercase-rtdb/main.py

+17-7
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
# [START all]
16+
from typing import Any
1617
from urllib import parse as urllib_parse
1718

1819
# [START import]
@@ -40,11 +41,12 @@ def addmessage(req: https_fn.Request) -> https_fn.Response:
4041
# [START adminSdkPush]
4142

4243
# Push the new message into the Realtime Database using the Firebase Admin SDK.
43-
ref = db.reference("/messages").push({"original": original})
44+
ref = db.reference("/messages").push({"original": original}) # type: ignore
4445

4546
# Redirect with 303 SEE OTHER to the URL of the pushed object.
46-
scheme, location, path, query, fragment = urllib_parse.urlsplit(
47-
app.options.get("databaseURL")
47+
scheme, location, path, query, fragment = (
48+
b.decode()
49+
for b in urllib_parse.urlsplit(app.options.get("databaseURL"))
4850
)
4951
path = f"{ref.path}.json"
5052
return https_fn.Response(
@@ -63,21 +65,25 @@ def addmessage(req: https_fn.Request) -> https_fn.Response:
6365

6466
# [START makeUppercase]
6567
@db_fn.on_value_created(reference="/messages/{pushId}/original")
66-
def makeuppercase(event: db_fn.Event[object]) -> None:
68+
def makeuppercase(event: db_fn.Event[Any]) -> None:
6769
"""Listens for new messages added to /messages/{pushId}/original and
6870
creates an uppercase version of the message to /messages/{pushId}/uppercase
6971
"""
7072

7173
# Grab the value that was written to the Realtime Database.
7274
original = event.data
73-
if not hasattr(original, "upper"):
75+
if not isinstance(original, str):
7476
print(f"Not a string: {event.reference}")
7577
return
7678

7779
# Use the Admin SDK to set an "uppercase" sibling.
7880
print(f"Uppercasing {event.params['pushId']}: {original}")
7981
upper = original.upper()
80-
db.reference(event.reference).parent.child("uppercase").set(upper)
82+
parent = db.reference(event.reference).parent
83+
if parent is None:
84+
print("Message can't be root node.")
85+
return
86+
parent.child("uppercase").set(upper)
8187

8288

8389
# [END makeUppercase]
@@ -107,7 +113,11 @@ def makeuppercase2(event: db_fn.Event[db_fn.Change]) -> None:
107113
# Use the Admin SDK to set an "uppercase" sibling.
108114
print(f"Uppercasing {event.params['pushId']}: {original}")
109115
upper = original.upper()
110-
db.reference(event.reference).parent.child("uppercase").set(upper)
116+
parent = db.reference(event.reference).parent
117+
if parent is None:
118+
print("Message can't be root node.")
119+
return
120+
parent.child("uppercase").set(upper)
111121

112122

113123
# [END makeUppercase2]

Python/taskqueues-backup-images/main.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,13 @@
2929
app = initialize_app()
3030

3131
BACKUP_START_DATE = datetime(1995, 6, 17)
32-
BACKUP_COUNT = params.IntParam("BACKUP_COUNT", default=100).value()
33-
HOURLY_BATCH_SIZE = params.IntParam("HOURLY_BATCH_SIZE", default=600).value()
32+
BACKUP_COUNT = params.IntParam("BACKUP_COUNT", default=100).value
33+
HOURLY_BATCH_SIZE = params.IntParam("HOURLY_BATCH_SIZE", default=600).value
3434
BACKUP_BUCKET = params.StringParam(
35-
"BACKUP_BUCKET", input=params.ResourceInput
36-
).value()
37-
NASA_API_KEY = params.StringParam("NASA_API_KEY").value()
35+
"BACKUP_BUCKET",
36+
input=params.ResourceInput(type=params.ResourceType.STORAGE_BUCKET),
37+
).value
38+
NASA_API_KEY = params.StringParam("NASA_API_KEY").value
3839

3940

4041
# [START v2TaskFunctionSetup]
@@ -82,6 +83,8 @@ def backupapod(req: tasks_fn.CallableRequest) -> str:
8283
print(f"Got URL {pic_url} from NASA API for date {date}. Fetching...")
8384
pic_resp = requests.get(pic_url)
8485
pic_type = pic_resp.headers.get("Content-Type")
86+
if pic_type is None:
87+
pic_type = "image/jpeg"
8588

8689
print("Uploading to Cloud Storage")
8790
bucket = storage.bucket(BACKUP_BUCKET)
@@ -105,7 +108,7 @@ def enqueuebackuptasks(_: https_fn.Request) -> https_fn.Response:
105108
"""Adds backup tasks to a Cloud Tasks queue."""
106109
tasks_client = tasks_v2.CloudTasksClient()
107110
task_queue = tasks_client.queue_path(
108-
params.PROJECT_ID.value(), SupportedRegion.US_CENTRAL1, "backupapod"
111+
params.PROJECT_ID.value, SupportedRegion.US_CENTRAL1, "backupapod"
109112
)
110113
target_uri = get_function_url("backupapod")
111114

Python/testlab-to-slack/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
def post_to_slack(title: str, details: str) -> requests.Response:
3131
"""Posts a message to Slack via a Webhook."""
3232
return requests.post(
33-
SLACK_WEBHOOK_URL.value(),
33+
SLACK_WEBHOOK_URL.value,
3434
json={
3535
"blocks": [
3636
{

0 commit comments

Comments
 (0)