Comments (7)
This is what I'm using right now. it doesn't play great with mypy (complains that it's not the google.lib.protobuf.Any) but otherwise it works for my JSON usecase:
@dataclass(eq=False, repr=False)
class Any(betterproto.Message):
type_url: str = betterproto.string_field(1)
value: betterproto.Message = betterproto.message_field(2)
def to_dict(
self, casing: betterproto.Casing = betterproto.Casing.CAMEL, include_default_values: bool = False
) -> Dict[str, Any]:
raw_dict = super().to_dict(casing, include_default_values)
dict_: Dict[str, Any] = {}
type_url = casing('type_url').rstrip("_") # type: ignore
if type_url in raw_dict:
dict_['@type'] = raw_dict[type_url]
value = casing('value').rstrip("_") # type: ignore
dict_.update(raw_dict.get(value, {}))
return dict_
from python-betterproto.
@Evgenus - You requested support for Any
Thanks for this PR. I trapped into that issue a hour ago. Please add also
import "google/protobuf/any.proto";
Originally posted by @Evgenus in #76 (comment)
Since I have no experience with Any, will simply importing it be enough? Or does it need special behavior when parsing an Any
message?
We could generate the Any object with url
and bytes
or fully decode it on the fly. Any thoughts on this?
from python-betterproto.
@boukeversteegh I saw you are involve in the some issues related to the support of Any
type.
Do you know if there's some news for supporting Any
in the coming releases ?
from python-betterproto.
I'm not actively participating in betterproto anymore, but seeing that no new comments were added here, it looks like there are no concrete plans for implementing it.
The first step would be to define what Any support would look like. You're very welcome to share what could be a useful form of support for your use case.
from python-betterproto.
Still needed. I am using it to interface with Envoy, which uses Any.
Modified above code to work with python 3.10:
def to_dict(
self, casing: betterproto.Casing = betterproto.Casing.SNAKE, include_default_values: bool = False
) -> Dict[str, object]:
raw_dict = super().to_dict(casing, include_default_values)
dict_: Dict[str, object] = {}
type_url = casing('type_url').rstrip("_") # type: ignore
if type_url in raw_dict:
dict_['@type'] = raw_dict[type_url]
value = casing('value').rstrip("_") # type: ignore
dict_.update(raw_dict.get(value, {}))
return dict_
from python-betterproto.
here is my usecase :
I have the following proto message answer :
message QueryAccountsResponse {
// accounts are the existing accounts
repeated google.protobuf.Any accounts = 1 [(cosmos_proto.accepts_interface) = "cosmos.auth.v1beta1.AccountI"];
// pagination defines the pagination in the response.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}
betterproto generate the folowing class:
@dataclass(eq=False, repr=False)
class QueryAccountResponse(betterproto.Message):
"""
QueryAccountResponse is the response type for the Query/Account RPC method.
"""
account: "betterproto_lib_google_protobuf.Any" = betterproto.message_field(1)
"""account defines the account of the corresponding address."""
When I request from a REST API, I'm getting the following answer :
{'account':
{
'@type': '/cosmos.auth.v1beta1.BaseAccount',
'account_number': '38',
'address': 'c4e1s3z7kvhtx8u7uruflz208phy5tuzhzlgv0h50k',
'pub_key': None,
'sequence': '0'
}
}
I'm loading my Message with the following line :
QueryAccountResponse().from_dict(json.loads(json_response))
and get an empty object as result.
How can I have the ANY object ?
from python-betterproto.
@sunds I am also looking into using this for an Envoy interface, but I do not have much experience using betterproto. Would it be possible for you to share a short example, how you use the modified Any class in your code, please? Thank you
[Update]: I think I figured it out. I included the wrong "Any" class
from python-betterproto.
Related Issues (20)
- Enum field is set to an integer by default
- Project Tox (poe full-test) setup can break under normal usage HOT 1
- How to enable @dataclass(eq=True, repr=True)? HOT 4
- pydantic v2 support HOT 1
- Dataclasses generated despite `--python_betterproto_opt=pydantic_dataclasses` HOT 2
- Path to 2.0 release? HOT 1
- TypeError: object AsyncChannel can't be used in 'await' expression
- Strip enum prefixes during compilation HOT 1
- SerializeToString Error for `List of List` HOT 1
- Inconsistency with google protobuf when converting to dict/json with include_default_values=True
- Nested message with repeated field not in to_json when mutated after initialization
- gRPC server example not working HOT 1
- Code Quality: mypy check failed HOT 1
- Complex protos w/ Enums? HOT 2
- Empty fields which one of None HOT 3
- `Struct().from_dict(...)` has no effect HOT 5
- Missing import in generated code when using well known types HOT 1
- Generated code has non-existent relative import HOT 3
- Error parsing proto with map field HOT 3
- Type error on server-side unary-unary handler code
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from python-betterproto.