Skip to content
This repository was archived by the owner on Feb 1, 2024. It is now read-only.

Commit fffc4a1

Browse files
authored
update Tasks Sample for App Engine [(#1541)](GoogleCloudPlatform/python-docs-samples#1541)
* update gcloud command for creating queues * deploys and runs * update license * passing tests
1 parent 438c65e commit fffc4a1

File tree

7 files changed

+75
-62
lines changed

7 files changed

+75
-62
lines changed

samples/appengine/flexible/tasks/README.md

+30-10
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ To set up authentication, please refer to our
3434

3535
To create a queue using the Cloud SDK, use the following gcloud command:
3636

37-
gcloud alpha tasks queues create-app-engine-queue my-appengine-queue
37+
```
38+
gcloud alpha tasks queues create app-engine my-appengine-queue
39+
```
3840

3941
Note: A newly created queue will route to the default App Engine service and
4042
version unless configured to do otherwise.
@@ -43,48 +45,66 @@ version unless configured to do otherwise.
4345

4446
Deploy the App Engine app with gcloud:
4547

46-
gcloud app deploy
48+
```
49+
gcloud app deploy
50+
```
4751

4852
Verify the index page is serving:
4953

50-
gcloud app browse
54+
```
55+
gcloud app browse
56+
```
5157

5258
The App Engine app serves as a target for the push requests. It has an
5359
endpoint `/log_payload` that reads the payload (i.e., the request body) of the
5460
HTTP POST request and logs it. The log output can be viewed with:
5561

56-
gcloud app logs read
62+
```
63+
gcloud app logs read
64+
```
5765

5866
## Running the Samples
5967

6068
Set environment variables:
6169

6270
First, your project ID:
6371

64-
export PROJECT_ID=my-project-id
72+
```
73+
export PROJECT_ID=my-project-id
74+
```
6575

6676
Then the queue ID, as specified at queue creation time. Queue IDs already
6777
created can be listed with `gcloud alpha tasks queues list`.
6878

69-
export QUEUE_ID=my-appengine-queue
79+
```
80+
export QUEUE_ID=my-appengine-queue
81+
```
7082

7183
And finally the location ID, which can be discovered with
7284
`gcloud alpha tasks queues describe $QUEUE_ID`, with the location embedded in
7385
the "name" value (for instance, if the name is
7486
"projects/my-project/locations/us-central1/queues/my-appengine-queue", then the
7587
location is "us-central1").
7688

77-
export LOCATION_ID=us-central1
89+
```
90+
export LOCATION_ID=us-central1
91+
```
7892

7993
Create a task, targeted at the `log_payload` endpoint, with a payload specified:
8094

81-
python create_app_engine_queue_task.py --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --payload=hello
95+
```
96+
python create_app_engine_queue_task.py --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --payload=hello
97+
```
8298

8399
Now view that the payload was received and verify the payload:
84100

85-
gcloud app logs read
101+
```
102+
gcloud app logs read
103+
```
86104

87105
Create a task that will be scheduled for a time in the future using the
88106
`--in_seconds` flag:
89107

90-
python create_app_engine_queue_task.py --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --payload=hello --in_seconds=30
108+
```
109+
python create_app_engine_queue_task.py --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --payload=hello --in_seconds=30
110+
```

samples/appengine/flexible/tasks/app.yaml

+14
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
# Copyright 2018 Google Inc. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
115
runtime: python
216
env: flex
317
entrypoint: gunicorn -b :$PORT main:app

samples/appengine/flexible/tasks/create_app_engine_queue_task.py

+19-30
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2017 Google Inc. All Rights Reserved.
1+
# Copyright 2018 Google Inc. All Rights Reserved.
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -15,62 +15,51 @@
1515
from __future__ import print_function
1616

1717
import argparse
18-
import base64
1918
import datetime
20-
import json
2119

2220

2321
# [START cloud_tasks_appengine_create_task]
2422
def create_task(project, queue, location, payload=None, in_seconds=None):
2523
"""Create a task for a given queue with an arbitrary payload."""
2624

27-
import googleapiclient.discovery
25+
from google.cloud import tasks_v2beta2
26+
from google.protobuf import timestamp_pb2
2827

2928
# Create a client.
30-
client = googleapiclient.discovery.build('cloudtasks', 'v2beta2')
29+
client = tasks_v2beta2.CloudTasksClient()
3130

3231
# Construct the request body.
33-
url = '/example_task_handler'
34-
body = {
35-
'task': {
36-
'appEngineHttpRequest': { # Specify the type of request.
37-
'httpMethod': 'POST',
38-
'relativeUrl': url
32+
task = {
33+
'app_engine_http_request': { # Specify the type of request.
34+
'http_method': 'POST',
35+
'relative_url': '/example_task_handler'
3936
}
40-
}
4137
}
42-
4338
if payload is not None:
44-
# The API expects base64 encoding of the payload, so encode the unicode
45-
# `payload` object into a byte string and base64 encode it.
46-
base64_encoded_payload = base64.b64encode(payload.encode())
47-
48-
# The request body object will be emitted in JSON, which requires
49-
# unicode objects, so convert the byte string to unicode, still base64.
50-
converted_payload = base64_encoded_payload.decode()
39+
# The API expects a payload of type bytes.
40+
converted_payload = payload.encode()
5141

5242
# Add the payload to the request.
53-
body['task']['appEngineHttpRequest']['payload'] = converted_payload
43+
task['app_engine_http_request']['payload'] = converted_payload
5444

5545
if in_seconds is not None:
5646
# Convert "seconds from now" into an rfc3339 datetime string.
5747
d = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)
58-
scheduled_time = d.isoformat('T') + 'Z'
48+
49+
# Create Timestamp protobuf.
50+
timestamp = timestamp_pb2.Timestamp()
51+
timestamp.FromDatetime(d)
5952

6053
# Add the rfc3339 datetime string to the request.
61-
body['task']['scheduleTime'] = scheduled_time
54+
task['schedule_time'] = timestamp
6255

6356
# Construct the fully qualified queue name.
64-
queue_name = 'projects/{}/locations/{}/queues/{}'.format(
65-
project, location, queue)
66-
67-
print('Sending task {}'.format(json.dumps(body)))
57+
parent = client.queue_path(project, location, queue)
6858

6959
# Use the client to build and send the task.
70-
response = client.projects().locations().queues().tasks().create(
71-
parent=queue_name, body=body).execute()
60+
response = client.create_task(parent, task)
7261

73-
print('Created task {}'.format(response['name']))
62+
print('Created task {}'.format(response.name))
7463
return response
7564
# [END cloud_tasks_appengine_create_task]
7665

Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2016 Google Inc. All Rights Reserved.
1+
# Copyright 2018 Google Inc. All Rights Reserved.
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -12,22 +12,16 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import mock
15+
import os
1616

1717
import create_app_engine_queue_task
1818

19-
TEST_PROJECT = 'mock-project'
20-
TEST_LOCATION = 'us-central1'
21-
TEST_QUEUE = 'my-appengine-queue'
19+
TEST_PROJECT_ID = os.getenv('GCLOUD_PROJECT')
20+
TEST_LOCATION = os.getenv('TEST_QUEUE_LOCATION', 'us-central1')
21+
TEST_QUEUE_NAME = os.getenv('TEST_QUEUE_NAME', 'my-appengine-queue')
2222

2323

24-
@mock.patch('googleapiclient.discovery.build')
25-
def test_create_task(build):
26-
projects = build.return_value.projects.return_value
27-
locations = projects.locations.return_value
28-
create_function = locations.queues.return_value.tasks.return_value.create
29-
execute_function = create_function.return_value.execute
30-
execute_function.return_value = {'name': 'task_name'}
31-
create_app_engine_queue_task.create_task(
32-
TEST_PROJECT, TEST_QUEUE, TEST_LOCATION)
33-
assert execute_function.called
24+
def test_create_task():
25+
result = create_app_engine_queue_task.create_task(
26+
TEST_PROJECT_ID, TEST_QUEUE_NAME, TEST_LOCATION)
27+
assert TEST_QUEUE_NAME in result.name

samples/appengine/flexible/tasks/main.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2016 Google Inc.
1+
# Copyright 2018 Google Inc.
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.

samples/appengine/flexible/tasks/main_test.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2016 Google Inc. All Rights Reserved.
1+
# Copyright 2018 Google Inc. All Rights Reserved.
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,2 @@
11
Flask==0.12.2
2-
google-api-python-client==1.6.5
3-
google-auth==1.4.1
4-
google-auth-httplib2==0.0.3
5-
google-cloud-datastore==1.6.0
6-
gunicorn==19.7.1
2+
google-cloud-tasks==0.2.0

0 commit comments

Comments
 (0)