Comments (11)
🎉 🎈 👍 !!
from marshmallow.
Using sqlalchemy, flask & marshmallow.
I also seem to have an issue when a sqlalchemy query result is as below:
Query: Hosts.query.orderby(Hosts.hostname).all()
hosts
[<main.Hosts object at 0x102b710d0>, <main.Hosts object at 0x102b6ea10>]Serializer(hosts, many=True).data
[collections.OrderedDict({}), collections.OrderedDict({})]Serializer(hosts, only=('hostname'), many=True).data
[collections.OrderedDict({'h': None, 'o': None, 's': None, 't': None, 'n': None, 'a': None, 'm': None, 'e': None }), collections.OrderedDict({'h': None, 'o': None, 's': None, 't': None, 'n': None, 'a': None, 'm': None, 'e': None })]
from marshmallow.
Can you post the code for your Serializer
class?
from marshmallow.
from marshmallow import Serializer
I am not using any other classes, from the docs it appears to be optional.
from marshmallow.
It is absolutely necessary to subclass Serializer
; it is how you define the output fields for the serializer. Can you point to the section of the documentation that was misleading?
Here is a working example using your above data:
import sqlalchemy
from marshmallow import Serializer, fields, pprint
labels = ['host', 'name', 'enabled']
modules = [sqlalchemy.util._collections.KeyedTuple((u'HostA', u'Backup', 1), labels=labels),
sqlalchemy.util._collections.KeyedTuple((u'HostA', u'Backup', 0), labels=labels),
sqlalchemy.util._collections.KeyedTuple((u'HostA', u'Backup', 0), labels=labels),
sqlalchemy.util._collections.KeyedTuple((u'HostA', u'Backup', 1), labels=labels)
]
class MySerializer(Serializer):
name = fields.String()
kind = fields.String()
enabled = fields.Boolean()
serialized = MySerializer(modules, many=True, only=('name', 'enabled'))
serialized.data
# {"name": "HostA", "enabled": true}
# {"name": "HostA", "enabled": false}
# {"name": "HostA", "enabled": false}
# {"name": "HostA", "enabled": true}
from marshmallow.
I have tried it like you have specified and it worked.
After rereading the docs it appears I have completely overlooked having to subclass Serializer.
Previously I had tried subclassing like this:
class MySerializer(Serializer):
class Meta:
fields = ('id', 'name', 'enabled')
But received an error when using the class:
TypeError: tuple indices must be integers, not str
As I now have it working I will keep it to how you have specified.
Thanks very much for your assistance!
from marshmallow.
Glad I could help.
Your issue actually brings up an issue that I had not found before: using the fields
option in class Meta
does not work for keyed tuples such as sqlalchemy's KeyedTuple
and collections.namedtuple
. Thanks for finding this! I will issue a fix soon.
from marshmallow.
Hey @sloria - I just ran into this again, with the fields & KeyedTuple. I think the issue is that it uses dir(). Here's a debugger session from that error, in marshmallow/utils.py:to_marshallable_type():
>>> obj
sqlalchemy.util._collections.KeyedTuple((3278477.5500000003, 29700, 0.04472251026943858, 0.8179699425486985, 0.4208957237122138, 0.8067728413148435, 2479, 3, ... ))
>>> dir(obj)
Traceback (most recent call last):
File "<debugger>", line 1, in <module>
dir(obj)
TypeError: unorderable types: NoneType() < str()
>>> obj.__dict__.keys()
dict_keys(['year', 'product_id', 'import_value', None, 'department_id', 'cog', 'coi', 'export_rca', 'export_value', 'id', '_labels'])
Sort of ...
I'm using class Meta: fields=[], and still seems to break.
from marshmallow.
And oddly specifying only=() doesn't seem to fix it for me as it did for you guys.
from marshmallow.
Thanks for reporting @makmanalp. I will look into this soon.
from marshmallow.
@sloria no, thank /you/!
from marshmallow.
Related Issues (20)
- Is this safer than Pickle? HOT 1
- Wrong value in __call__() function of validate.Validator HOT 1
- Validation of required nested field is not consistent with previous version
- Create raw list Schema HOT 1
- The function decorated by the "post_load" decorator will undergo changes in parameter types as the function name changes. HOT 1
- Deprecate __version__ and related attributes
- Address deprecation warnings in tests HOT 1
- URL validation fails if URL is missing user field HOT 5
- fields.URL validation error should specify "not a valid FQDN" if trying to pass hostname without domain
- missing `f` for f-Strings HOT 2
- `fields.Url` does not accept `file` URLs
- when a new request, schema context not reset !!! HOT 2
- Questions about Copilot + Open Source Software Hierarchy HOT 3
- Allow None for a allow_none=True Date field HOT 6
- fields.Nested Type Warning Since Version 3.15.0
- Setting many=True through Meta - SchemaOpts HOT 1
- RFE: use `zoneinfo` instead of `pytz` HOT 3
- 3.21.2: pytest fails in units checking time HOT 1
- 3.21.2: sphinx warnings `reference target not found` HOT 2
- Static typing of Field subclass kwargs
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 marshmallow.