|
| 1 | +# All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 | +# not use this file except in compliance with the License. You may obtain |
| 5 | +# 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, WITHOUT |
| 11 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | +# License for the specific language governing permissions and limitations |
| 13 | +# under the License. |
| 14 | + |
| 15 | +import json |
| 16 | +import requests |
| 17 | +import sys |
| 18 | + |
| 19 | +from cloudevents.sdk import converters |
| 20 | +from cloudevents.sdk import marshaller |
| 21 | + |
| 22 | +from cloudevents.sdk.event import v02 |
| 23 | + |
| 24 | + |
| 25 | +def run_binary(event, url): |
| 26 | + binary_headers, binary_data = http_marshaller.ToRequest( |
| 27 | + event, converters.TypeBinary, json.dumps) |
| 28 | + |
| 29 | + print("binary CloudEvent") |
| 30 | + for k, v in binary_headers.items(): |
| 31 | + print("{0}: {1}\r\n".format(k, v)) |
| 32 | + print(binary_data.getvalue()) |
| 33 | + response = requests.post(url, |
| 34 | + headers=binary_headers, |
| 35 | + data=binary_data.getvalue()) |
| 36 | + response.raise_for_status() |
| 37 | + |
| 38 | + |
| 39 | +def run_structured(event, url): |
| 40 | + structured_headers, structured_data = http_marshaller.ToRequest( |
| 41 | + event, converters.TypeStructured, json.dumps |
| 42 | + ) |
| 43 | + print("structured CloudEvent") |
| 44 | + print(structured_data.getvalue()) |
| 45 | + |
| 46 | + response = requests.post(url, |
| 47 | + headers=structured_headers, |
| 48 | + data=structured_data.getvalue()) |
| 49 | + response.raise_for_status() |
| 50 | + |
| 51 | + |
| 52 | +if __name__ == "__main__": |
| 53 | + |
| 54 | + if len(sys.argv) < 3: |
| 55 | + sys.exit("Usage: python with_requests.py " |
| 56 | + "[binary | structured] " |
| 57 | + "<CloudEvents controller URL>") |
| 58 | + |
| 59 | + fmt = sys.argv[1] |
| 60 | + url = sys.argv[2] |
| 61 | + |
| 62 | + http_marshaller = marshaller.NewDefaultHTTPMarshaller() |
| 63 | + event = ( |
| 64 | + v02.Event(). |
| 65 | + SetContentType("application/json"). |
| 66 | + SetData({"name": "denis"}). |
| 67 | + SetEventID("my-id"). |
| 68 | + SetSource("<event-source"). |
| 69 | + SetEventType("cloudevent.event.type") |
| 70 | + ) |
| 71 | + if "structured" == fmt: |
| 72 | + run_structured(event, url) |
| 73 | + elif "binary" == fmt: |
| 74 | + run_binary(event, url) |
| 75 | + else: |
| 76 | + sys.exit("unknown format: {0}".format(fmt)) |
0 commit comments