|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +# Copyright 2020 Google Inc. All Rights Reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the 'License'); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | + |
| 17 | +import sys |
| 18 | + |
| 19 | +# [START storage_generate_signed_post_policy_v4] |
| 20 | +from google.cloud import storage |
| 21 | +import datetime |
| 22 | + |
| 23 | + |
| 24 | +def generate_signed_post_policy_v4(bucket_name, blob_name): |
| 25 | + """Generates a v4 POST Policy and prints an HTML form.""" |
| 26 | + # bucket_name = 'your-bucket-name' |
| 27 | + # blob_name = 'your-object-name' |
| 28 | + |
| 29 | + storage_client = storage.Client() |
| 30 | + |
| 31 | + policy = storage_client.generate_signed_post_policy_v4( |
| 32 | + bucket_name, |
| 33 | + blob_name, |
| 34 | + expiration=datetime.timedelta(minutes=10), |
| 35 | + fields={ |
| 36 | + 'x-goog-meta-test': 'data' |
| 37 | + } |
| 38 | + ) |
| 39 | + |
| 40 | + # Create an HTML form with the provided policy |
| 41 | + header = "<form action='{}' method='POST' enctype='multipart/form-data'>\n" |
| 42 | + form = header.format(policy["url"]) |
| 43 | + |
| 44 | + # Include all fields returned in the HTML form as they're required |
| 45 | + for key, value in policy["fields"].items(): |
| 46 | + form += " <input name='{}' value='{}' type='hidden'/>\n".format(key, value) |
| 47 | + |
| 48 | + form += " <input type='file' name='file'/><br />\n" |
| 49 | + form += " <input type='submit' value='Upload File' name='submit'/><br />\n" |
| 50 | + form += "</form>" |
| 51 | + |
| 52 | + print(form) |
| 53 | + |
| 54 | + return form |
| 55 | + |
| 56 | + |
| 57 | +# [END storage_generate_signed_post_policy_v4] |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + generate_signed_post_policy_v4( |
| 61 | + bucket_name=sys.argv[1], blob_name=sys.argv[2] |
| 62 | + ) |
0 commit comments