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

Commit adf9218

Browse files
authored
[Cloud Tasks] Move samples to new folder [(#2114)](GoogleCloudPlatform/python-docs-samples#2114)
* Move samples to keep consistent with other langauges * Ad system tests as well
1 parent d361fc2 commit adf9218

File tree

4 files changed

+264
-0
lines changed

4 files changed

+264
-0
lines changed

samples/snippets/README.md

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Google Cloud Tasks Samples
2+
3+
[![Open in Cloud Shell][shell_img]][shell_link]
4+
5+
[shell_img]: http://gstatic.com/cloudssh/images/open-btn.png
6+
[shell_link]: https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/GoogleCloudPlatform/python-docs-samples&page=editor&open_in_editor=appengine/flexible/tasks/README.md
7+
8+
Sample command-line programs for interacting with the Cloud Tasks API
9+
.
10+
11+
App Engine queues push tasks to an App Engine HTTP target. This directory
12+
contains both the App Engine app to deploy, as well as the snippets to run
13+
locally to push tasks to it, which could also be called on App Engine.
14+
15+
`create_app_engine_queue_task.py` is a simple command-line program to create
16+
tasks to be pushed to the App Engine app.
17+
18+
`main.py` is the main App Engine app. This app serves as an endpoint to receive
19+
App Engine task attempts.
20+
21+
`app.yaml` configures the App Engine app.
22+
23+
24+
## Prerequisites to run locally:
25+
26+
Please refer to [Setting Up a Python Development Environment](https://cloud.google.com/python/setup).
27+
28+
## Authentication
29+
30+
To set up authentication, please refer to our
31+
[authentication getting started guide](https://cloud.google.com/docs/authentication/getting-started).
32+
33+
## Creating a queue
34+
35+
To create a queue using the Cloud SDK, use the following gcloud command:
36+
37+
```
38+
gcloud beta tasks queues create-app-engine-queue my-appengine-queue
39+
```
40+
41+
Note: A newly created queue will route to the default App Engine service and
42+
version unless configured to do otherwise.
43+
44+
## Deploying the App Engine App
45+
46+
Deploy the App Engine app with gcloud:
47+
48+
* To deploy to the Standard environment:
49+
```
50+
gcloud app deploy app.yaml
51+
```
52+
* To deploy to the Flexible environment:
53+
```
54+
gcloud app deploy app.flexible.yaml
55+
```
56+
57+
Verify the index page is serving:
58+
59+
```
60+
gcloud app browse
61+
```
62+
63+
The App Engine app serves as a target for the push requests. It has an
64+
endpoint `/example_task_handler` that reads the payload (i.e., the request body)
65+
of the HTTP POST request and logs it. The log output can be viewed with:
66+
67+
```
68+
gcloud app logs read
69+
```
70+
71+
## Run the Sample Using the Command Line
72+
73+
Set environment variables:
74+
75+
First, your project ID:
76+
77+
```
78+
export PROJECT_ID=my-project-id
79+
```
80+
81+
Then the queue ID, as specified at queue creation time. Queue IDs already
82+
created can be listed with `gcloud beta tasks queues list`.
83+
84+
```
85+
export QUEUE_ID=my-appengine-queue
86+
```
87+
88+
And finally the location ID, which can be discovered with
89+
`gcloud beta tasks queues describe $QUEUE_ID`, with the location embedded in
90+
the "name" value (for instance, if the name is
91+
"projects/my-project/locations/us-central1/queues/my-appengine-queue", then the
92+
location is "us-central1").
93+
94+
```
95+
export LOCATION_ID=us-central1
96+
```
97+
98+
### Using HTTP Push Queues
99+
100+
Set an environment variable for the endpoint to your task handler. This is an
101+
example url to send requests to the App Engine task handler:
102+
```
103+
export URL=https://<project_id>.appspot.com/example_task_handler
104+
```
105+
106+
Running the sample will create a task and send the task to the specific URL
107+
endpoint, with a payload specified:
108+
109+
```
110+
python create_http_task.py --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --url=$URL --payload=hello
111+
```

samples/snippets/create_http_task.py

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# Copyright 2019 Google LLC 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+
15+
from __future__ import print_function
16+
17+
import argparse
18+
import datetime
19+
20+
21+
def create_http_task(project,
22+
queue,
23+
location,
24+
url,
25+
payload=None,
26+
in_seconds=None):
27+
# [START cloud_tasks_create_http_task]
28+
"""Create a task for a given queue with an arbitrary payload."""
29+
30+
from google.cloud import tasks_v2beta3
31+
from google.protobuf import timestamp_pb2
32+
33+
# Create a client.
34+
client = tasks_v2beta3.CloudTasksClient()
35+
36+
# TODO(developer): Uncomment these lines and replace with your values.
37+
# project = 'my-project-id'
38+
# queue = 'my-appengine-queue'
39+
# location = 'us-central1'
40+
# url = 'https://<project-id>.appspot.com/example_task_handler'
41+
# payload = 'hello'
42+
43+
# Construct the fully qualified queue name.
44+
parent = client.queue_path(project, location, queue)
45+
46+
# Construct the request body.
47+
task = {
48+
'http_request': { # Specify the type of request.
49+
'http_method': 'POST',
50+
'url': url # The full url path that the task will be sent to.
51+
}
52+
}
53+
if payload is not None:
54+
# The API expects a payload of type bytes.
55+
converted_payload = payload.encode()
56+
57+
# Add the payload to the request.
58+
task['http_request']['body'] = converted_payload
59+
60+
if in_seconds is not None:
61+
# Convert "seconds from now" into an rfc3339 datetime string.
62+
d = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)
63+
64+
# Create Timestamp protobuf.
65+
timestamp = timestamp_pb2.Timestamp()
66+
timestamp.FromDatetime(d)
67+
68+
# Add the timestamp to the tasks.
69+
task['schedule_time'] = timestamp
70+
71+
# Use the client to build and send the task.
72+
response = client.create_task(parent, task)
73+
74+
print('Created task {}'.format(response.name))
75+
return response
76+
# [END cloud_tasks_create_http_task]
77+
78+
79+
if __name__ == '__main__':
80+
parser = argparse.ArgumentParser(
81+
description=create_http_task.__doc__,
82+
formatter_class=argparse.RawDescriptionHelpFormatter)
83+
84+
parser.add_argument(
85+
'--project',
86+
help='Project of the queue to add the task to.',
87+
required=True,
88+
)
89+
90+
parser.add_argument(
91+
'--queue',
92+
help='ID (short name) of the queue to add the task to.',
93+
required=True,
94+
)
95+
96+
parser.add_argument(
97+
'--location',
98+
help='Location of the queue to add the task to.',
99+
required=True,
100+
)
101+
102+
parser.add_argument(
103+
'--url',
104+
help='The full url path that the request will be sent to.',
105+
required=True,
106+
)
107+
108+
parser.add_argument(
109+
'--payload',
110+
help='Optional payload to attach to the push queue.'
111+
)
112+
113+
parser.add_argument(
114+
'--in_seconds', type=int,
115+
help='The number of seconds from now to schedule task attempt.'
116+
)
117+
118+
args = parser.parse_args()
119+
120+
create_http_task(
121+
args.project, args.queue, args.location, args.url,
122+
args.payload, args.in_seconds)
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Copyright 2019 Google LLC 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+
15+
import os
16+
17+
import create_http_task
18+
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')
22+
23+
24+
def test_create_http_task():
25+
url = 'https://example.appspot.com/example_task_handler'
26+
result = create_http_task.create_http_task(
27+
TEST_PROJECT_ID, TEST_QUEUE_NAME, TEST_LOCATION, url)
28+
assert TEST_QUEUE_NAME in result.name

samples/snippets/requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Flask==1.0.2
2+
gunicorn==19.9.0
3+
google-cloud-tasks==0.6.0

0 commit comments

Comments
 (0)