Use bytes instead of Any in RunnerApi.FunctionSpec
[beam.git] / sdks / python / apache_beam / utils / proto_utils.py
1 #
2 # Licensed to the Apache Software Foundation (ASF) under one or more
3 # contributor license agreements. See the NOTICE file distributed with
4 # this work for additional information regarding copyright ownership.
5 # The ASF licenses this file to You under the Apache License, Version 2.0
6 # (the "License"); you may not use this file except in compliance with
7 # the License. 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
18 """For internal use only; no backwards-compatibility guarantees."""
19
20 from google.protobuf import any_pb2
21 from google.protobuf import struct_pb2
22
23
24 def pack_Any(msg):
25 """Creates a protobuf Any with msg as its content.
26
27 Returns None if msg is None.
28 """
29 if msg is None:
30 return None
31
32 result = any_pb2.Any()
33 result.Pack(msg)
34 return result
35
36
37 def unpack_Any(any_msg, msg_class):
38 """Unpacks any_msg into msg_class.
39
40 Returns None if msg_class is None.
41 """
42 if msg_class is None:
43 return None
44 msg = msg_class()
45 any_msg.Unpack(msg)
46 return msg
47
48
49 def parse_Bytes(bytes, msg_class):
50 """Parses the String of bytes into msg_class.
51
52 Returns the input bytes if msg_class is None."""
53 if msg_class is None:
54 return bytes
55 msg = msg_class()
56 msg.ParseFromString(bytes)
57 return msg
58
59
60 def pack_Struct(**kwargs):
61 """Returns a struct containing the values indicated by kwargs.
62 """
63 msg = struct_pb2.Struct()
64 for key, value in kwargs.items():
65 msg[key] = value # pylint: disable=unsubscriptable-object, unsupported-assignment-operation
66 return msg
67
68
69 def from_micros(cls, micros):
70 result = cls()
71 result.FromMicroseconds(micros)
72 return result