Flask + marshmallow for beautiful APIs

Overview

Flask-Marshmallow

Latest version Build status Documentation marshmallow 3 compatible code style: black

Flask + marshmallow for beautiful APIs

Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.

Get it now

pip install flask-marshmallow

Create your app.

from flask import Flask
from flask_marshmallow import Marshmallow

app = Flask(__name__)
ma = Marshmallow(app)

Write your models.

from your_orm import Model, Column, Integer, String, DateTime


class User(Model):
    email = Column(String)
    password = Column(String)
    date_created = Column(DateTime, auto_now_add=True)

Define your output format with marshmallow.

class UserSchema(ma.Schema):
    class Meta:
        # Fields to expose
        fields = ("email", "date_created", "_links")

    # Smart hyperlinking
    _links = ma.Hyperlinks(
        {
            "self": ma.URLFor("user_detail", values=dict(id="<id>")),
            "collection": ma.URLFor("users"),
        }
    )


user_schema = UserSchema()
users_schema = UserSchema(many=True)

Output the data in your views.

@app.route("/api/users/")
def users():
    all_users = User.all()
    return users_schema.dump(all_users)


@app.route("/api/users/<id>")
def user_detail(id):
    user = User.get(id)
    return user_schema.dump(user)


# {
#     "email": "[email protected]",
#     "date_created": "Fri, 25 Apr 2014 06:02:56 -0000",
#     "_links": {
#         "self": "/api/users/42",
#         "collection": "/api/users/"
#     }
# }

http://flask-marshmallow.readthedocs.io/

Learn More

To learn more about marshmallow, check out its docs.

Project Links

License

MIT licensed. See the bundled LICENSE file for more details.

Issues
  • AttributeError: 'Marshmallow' object has no attribute 'ModelSchema'

    AttributeError: 'Marshmallow' object has no attribute 'ModelSchema'

    Using the latest 0.7.0. I installed the build on a different machine and I only get this error on this machine.

    Upon inspecting the module, marshmallow indeed does NOT have a ModelSchema. Is this a bug or have I screwed something up? I haven't upgraded anything and I don't get this error on a different machine (both are running the latest Ubuntu 16 LTS)

    Out[2]: <flask_marshmallow.Marshmallow at 0x7f96d8f2a9b0>
    
    In [3]: vars(marshmallow)
    Out[3]: 
    {'AbsoluteURLFor': flask_marshmallow.fields.AbsoluteURLFor,
     'AbsoluteUrlFor': flask_marshmallow.fields.AbsoluteURLFor,
     'Bool': marshmallow.fields.Boolean,
     'Boolean': marshmallow.fields.Boolean,
     'Constant': marshmallow.fields.Constant,
     'Date': marshmallow.fields.Date,
     'DateTime': marshmallow.fields.DateTime,
     'Decimal': marshmallow.fields.Decimal,
     'Dict': marshmallow.fields.Dict,
     'Email': marshmallow.fields.Email,
     'Field': marshmallow.fields.Field,
     'Float': marshmallow.fields.Float,
     'FormattedString': marshmallow.fields.FormattedString,
     'Function': marshmallow.fields.Function,
     'Hyperlinks': flask_marshmallow.fields.Hyperlinks,
     'Int': marshmallow.fields.Integer,
     'Integer': marshmallow.fields.Integer,
     'List': marshmallow.fields.List,
     'LocalDateTime': marshmallow.fields.LocalDateTime,
     'Method': marshmallow.fields.Method,
     'Nested': marshmallow.fields.Nested,
     'Number': marshmallow.fields.Number,
     'Raw': marshmallow.fields.Raw,
     'Schema': flask_marshmallow.schema.Schema,
     'Str': marshmallow.fields.String,
     'String': marshmallow.fields.String,
     'Time': marshmallow.fields.Time,
     'TimeDelta': marshmallow.fields.TimeDelta,
     'URL': marshmallow.fields.Url,
     'URLFor': flask_marshmallow.fields.URLFor,
     'UUID': marshmallow.fields.UUID,
     'Url': marshmallow.fields.Url,
     'UrlFor': flask_marshmallow.fields.URLFor}
    

    Thanks.

    opened by Protosac 13
  • schema.jsonify list of sqlalchemy instances incompatible with flask.jsonify

    schema.jsonify list of sqlalchemy instances incompatible with flask.jsonify

    @ElvisTheKing @sloria

    continuing where #19 left off...

    I am trying to use flask-marshmallow schema.jsonify on the result of a sqlalchemy query

    Using model instance is ok

    from models.equipment import Equipment
    equipments = Equipment.query.all()
    equipments_schema.jsonify(equipments[0]).response
    
    #('{\n  "date_added": "2015-10-23T11:07:46.384414+00:00", \n  "id": 1, \n  "name": "beacon"\n}', '\n')
    

    List of model instances breaks

    equipments_schema.jsonify(equipments)
    
    #*** AttributeError: "id" is not a valid field for [<app.models.equipment.Equipment object at 0x7f5b3c11c240>, <app.models.equipment.Equipment object at 0x7f5b3c11cba8>].
    

    versions

    Flask==0.10.1
    flask-marshmallow==0.6.2
    -e git+https://github.com/flask-restful/[email protected]#egg=Flask_RESTful-master
    Flask-SQLAlchemy==2.0
    marshmallow==2.1.3
    marshmallow-sqlalchemy==0.6.0
    

    I think it's because the sqlalchemy query returns a list of model instances, which is not compatible with flask.jsonify. There's some discussion in flask about this, but it sounds like that'll never be supported.

    Am I missing something here? from the examples in the readme one might assume this should work.

    Otherwise, any thoughts for how to improve this?

    opened by jo-tham 11
  • Validation does not raise a ValidationError

    Validation does not raise a ValidationError

    When serializing data using Schema().load, a ValidationError does not get raised; instead, I get an UnmarshalResult object with the data and errors. Is this the expected output? does flask-marshmallow not raise a ValidationError when there are errors in the submitted data?

    Example:

    >>> from project.schemas import TermSchema
    >>> term_schema = TermSchema()
    >>> term_data = dict(term=None)
    >>> term_schema.load(term_data)
    UnmarshalResult(data={}, errors={'term': ['Field may not be null.']})
    

    Why is it returning an UnmarshalResult object instead of raising a validation error?

    Here is the schemas.py:

    from marshmallow import post_load
    from project.models import Term, Translation
    from flask_marshmallow import Marshmallow
    from marshmallow_sqlalchemy import field_for
    
    ma = Marshmallow()
    
    class TranslationSchema(ma.ModelSchema):
        class Meta:
            model = Translation
    
    class TermSchema(ma.ModelSchema):
        term = field_for(Term, 'term', required=True)
    
        class Meta:
            model = Term
        translations = ma.Nested(TranslationSchema, many=True)
    
        # Validate term is not none
        # Validate full_term is not none if is_acronym
        @post_load
        def make_term(self, data):
            return data
    
    opened by adyouri 11
  • Is there a specific way to format datetime in json?

    Is there a specific way to format datetime in json?

    Is there a specific way to format datetime in json?

    Some of my json dates come out as "Tue, 22 Sep 2015 10:17:00 GMT" and some come out as "2015-02-03T15:40:36.078358+00:00"

    opened by rlam3 10
  • Can you dynamically exclude fields on dump?

    Can you dynamically exclude fields on dump?

    I have some nested schemas:

    class ParentSchema(Schema):
        id = fields.Int()
        uri = fields.Url('')
        children = fields.Nested('ChildSchema', many=True, exclude=('parent',))
    
    class ChildSchema(Schema):
        id = fields.Int()
        f = fields.String()
        parent = fields.Nested('ParentSchema', exclude=('children',))
    

    It all works fine except that when I'm calling dump on the schema, calling parent.children results in a ginormous database query. The object being dumped is a SqlAlechemy object, and calling its children property results in lazy loading of those children from the database. The code looks like this:

    parents = Parent.all()
    schema = GameSchema()
    results = schema.dump(parents, many=True)
    

    I this particular case, I only need the parent records. Loading the children is wasted effort. There are, however cases, when I do need the children to be loaded. For this reason, I can't just put load_only on the nested fields in the schema definitions.

    Is there any way to tell one call to dump to skip certain fields?

    opened by dland512 10
  • from marshmallow import ( ImportError: cannot import name fields

    from marshmallow import ( ImportError: cannot import name fields

    I´m getting this when i try to run my project with Flask in a virtualenv

    Traceback (most recent call last): File "manage.py", line 10, in from flask_marshmallow import Marshmallow File "C:\Users\hcontreras\Documents\virtuales\MarketingProject\lib\site-packages\flask_marshmallow_init_.py", line 14, in from marshmallow import ( ImportError: cannot import name fields

    opened by handersonc 9
  • update hyperlinkrelated to gracefully support nullable / non-required sqla relations

    update hyperlinkrelated to gracefully support nullable / non-required sqla relations

    I have nullable relations on my SQLAlchemy models that blow up when deserializing HyperlinkRelated. Patch allows for graceful failure when base field is not-required.

    Similar to the issue listed here: https://github.com/marshmallow-code/flask-marshmallow/issues/18

    opened by feigner 8
  • return self.session.query( AttributeError: 'DummySession' object has no attribute 'query'

    return self.session.query( AttributeError: 'DummySession' object has no attribute 'query'

    Hey guys, this is my first post of publication and I speak Spanish, I am very sorry if you do not understand me clearly, this is my problem I am using flask-marshmallow in its version 0.9.0 and when I create my table if I add primary_key = True to any field that is not id (Integer) like social number I get this error (Title), and this error:

    Traceback (most recent call last):
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 2309, in __call__
        return self.wsgi_app(environ, start_response)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 2295, in wsgi_app
        response = self.handle_exception(e)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask_restful\__init__.py", line 273, in error_router
        return original_handler(e)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 1741, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\_compat.py", line 34, in reraise
        raise value.with_traceback(tb)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 2292, in wsgi_app
        response = self.full_dispatch_request()
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
        rv = self.handle_user_exception(e)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask_restful\__init__.py", line 273, in error_router
        return original_handler(e)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
        reraise(exc_type, exc_value, tb)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\_compat.py", line 34, in reraise
        raise value.with_traceback(tb)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
        rv = self.dispatch_request()
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\app.py", line 1799, in dispatch_request
        return self.view_functions[rule.endpoint](**req.view_args)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask_restful\__init__.py", line 480, in wrapper
        resp = resource(*args, **kwargs)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask\views.py", line 88, in view
        return self.dispatch_request(*args, **kwargs)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
        resp = meth(*args, **kwargs)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\flask_jwt_extended\view_decorators.py", line 103, in wrapper
        return fn(*args, **kwargs)
      File "C:\Users\user\Documents\OverBit\Apiv2\resource\student.py", line 41, in post
        student=student_schema.load(student_data)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow_sqlalchemy\schema.py", line 194, in load
        return super(ModelSchema, self).load(data, *args, **kwargs)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow\schema.py", line 504, in load
        postprocess=True,
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow\schema.py", line 640, in _do_load
        original_data=data,
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow\schema.py", line 820, in _invoke_load_processors
        data=data, many=many, original_data=original_data,
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow\schema.py", line 938, in _invoke_processors
        data = processor(data)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow_sqlalchemy\schema.py", line 176, in make_instance
        instance = self.instance or self.get_instance(data)
      File "C:\Users\user\.virtualenvs\Apiv2-zDC9aQiw\lib\site-packages\marshmallow_sqlalchemy\schema.py", line 161, in get_instance
        return self.session.query(
    AttributeError: 'DummySession' object has no attribute 'query'
    

    this error is fixed just when my primary key is id (int) Is there a way for my primary key to be a string?

    opened by dani16antonio 8
  • Integration of Flask, Flask-marshmallow and MongoAlchemy

    Integration of Flask, Flask-marshmallow and MongoAlchemy

    Hello, I tried the following code:

    from flask import Flask, request
    from flask_mongoalchemy import MongoAlchemy
    from flask_marshmallow import Marshmallow
    
    app = Flask(__name__)
    app.config['MONGOALCHEMY_DATABASE'] = 'flask-alchemy'
    app.config['MONGOALCHEMY_USER'] = 'user'
    app.config['MONGOALCHEMY_PASSWORD'] = 'password'
    app.config['MONGOALCHEMY_SERVER_AUTH'] = False
    db = MongoAlchemy(app)
    ma = Marshmallow(app)
    
    class Author(db.Document):
        name = db.StringField()
    
    class AuthorSchema(ma.ModelSchema):
        class Meta:
            model = Author
    
    author_schema = AuthorSchema()
    authors_schema = AuthorSchema(many=True)
    
    # mark_pilgrim = Author(name='Mark Pilgrim')
    # mark_pilgrim.save()
    
    @app.route("/author", methods=['POST'])
    def addUser():
        # author = Author(name=request.json['name'])
        author_result = author_schema.load(request.json)
        author_result.data.save()
        return "OK"
    
    @app.route("/author/<id>", methods=['GET'])
    def getUser(id):
        author = Author.query.get(id)
        return author_schema.jsonify(author)
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=9090)
    

    But application is not starting because of following error:

    Traceback (most recent call last):
      File "/home/nurgasemetey/IDES/pycharm-2017.2/helpers/pydev/pydevd.py", line 1596, in <module>
        globals = debugger.run(setup['file'], None, None, is_module)
      File "/home/nurgasemetey/IDES/pycharm-2017.2/helpers/pydev/pydevd.py", line 1023, in run
        pydev_imports.execfile(file, globals, locals)  # execute the script
      File "/media/nurgasemetey/2321222d-3af5-46b5-b8c5-824322db7a26/nurgasemetey-environment/PyCharm/PYCHARM_PROJECTS/flask-alchemy-mongo/Test.py", line 16, in <module>
        class AuthorSchema(ma.ModelSchema):
      File "/usr/local/lib/python2.7/dist-packages/marshmallow/schema.py", line 118, in __new__
        dict_cls=dict_cls
      File "/usr/local/lib/python2.7/dist-packages/marshmallow_sqlalchemy/schema.py", line 60, in get_declared_fields
        declared_fields = mcs.get_fields(converter, opts, base_fields, dict_cls)
      File "/usr/local/lib/python2.7/dist-packages/marshmallow_sqlalchemy/schema.py", line 94, in get_fields
        dict_cls=dict_cls,
      File "/usr/local/lib/python2.7/dist-packages/marshmallow_sqlalchemy/convert.py", line 93, in fields_for_model
        for prop in model.__mapper__.iterate_properties:
    AttributeError: type object 'Author' has no attribute '__mapper
    

    What can be wrong?

    Versions

    Flask==0.12 flask-marshmallow==0.8.0 Flask-MongoAlchemy==0.7.2 SQLAlchemy==1.1.11

    opened by nurgasemetey 6
  • Got Vulnerability while feeding request.get_json() data to marshmallow directly .

    Got Vulnerability while feeding request.get_json() data to marshmallow directly .

    I am using flask-marshmallow for user input validation .

    from marshmallow import Schema, fields, validate
    
    
    class UserSchema(Schema):
        username = fields.String(required=True,
                                validate=[validate.Length(min=1, error="Field should not be empty.")])
        pincode = fields.Integer(required=True, validate=validate.Range(
            min=0, error="pincode is invalid, it should be a positive integer."))
    

    In application controller part :

    class UserDetails(Resource):
        user_schema_obj = UserSchema()
        def post(self):
            if not request.is_json:
                return make_response(jsonify(error_dict(
                    current_request_id(), "Unsupported media type, Requests must be JSON",
                    415)), status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)
    
            if not request.json:
                return make_response(jsonify(error_dict(
                    current_request_id(), "Required parameter not found",
                    400)), status.HTTP_400_BAD_REQUEST)
            request_jsn = UserDetails.user_schema_obj.load(request.get_json())
            username = request_jsn['username']
            pincode = request_jsn['pincode']
    

    This is the way i am feeding user input to marshmallow schema . when i am doing app scan it saying gets user input from element **get_json**. This element’s value flows through the code without being properly sanitized or validated and is eventually stored in the server-side Session object, in post. This constitutes a Trust Boundary Violation. Dont know how to resolve this ? Please help!

    opened by vvksahoo 5
  • Bump sphinx from 3.5.4 to 4.1.1

    Bump sphinx from 3.5.4 to 4.1.1

    Bumps sphinx from 3.5.4 to 4.1.1.

    Changelog

    Sourced from sphinx's changelog.

    Release 4.1.1 (released Jul 15, 2021)

    Dependencies

    • #9434: sphinxcontrib-htmlhelp-2.0.0 or above
    • #9434: sphinxcontrib-serializinghtml-1.1.5 or above

    Bugs fixed

    • #9438: html: HTML logo or Favicon specified as file not being found on output

    Release 4.1.0 (released Jul 12, 2021)

    Dependencies

    • Support jinja2-3.0

    Deprecated

    • The app argument of sphinx.environment.BuildEnvironment becomes required
    • sphinx.application.Sphinx.html_theme
    • sphinx.ext.autosummary._app
    • sphinx.util.docstrings.extract_metadata()

    Features added

    • #8107: autodoc: Add class-doc-from option to :rst:dir:autoclass directive to control the content of the specific class like :confval:autoclass_content
    • #8588: autodoc: :confval:autodoc_type_aliases now supports dotted name. It allows you to define an alias for a class with module name like foo.bar.BazClass
    • #9175: autodoc: Special member is not documented in the module
    • #9195: autodoc: The arguments of typing.Literal are wrongly rendered
    • #9185: autodoc: :confval:autodoc_typehints allows 'both' setting to allow typehints to be included both in the signature and description
    • #4257: autodoc: Add :confval:autodoc_class_signature to separate the class entry and the definition of __init__() method
    • #8061, #9218: autodoc: Support variable comment for alias classes
    • #3014: autodoc: Add :event:autodoc-process-bases to modify the base classes of the class definitions
    • #9272: autodoc: Render enum values for the default argument value better

    ... (truncated)

    Commits
    • 564439e Bump to 4.1.1 final
    • ffa0831 Merge pull request #9448 from tk0miya/9434_update_deps
    • 5daedcf Fix #9434: Update dependencies for bundled builders
    • f3a3bd2 Update CHANGES for PR #9440
    • 63001f3 Merge pull request #9440 from tronical/logo-regression-fix
    • 3a50abc Fix handling of local paths in html_logo/html_favicon directorives in conf.py
    • 3c3a734 Bump version
    • bdcd161 Bump to 4.1.0 final
    • 4a2f5df Merge branch '9299' into 4.x
    • e6d3adf intersphinx: Add testcase for case insensitive term match (refs: #9299)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.

    Dependabot will not automatically merge this PR because it includes a major update to a development dependency.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language
    • @dependabot badge me will comment on this PR with code to add a "Dependabot enabled" badge to your readme

    Additionally, you can set the following in your Dependabot dashboard:

    • Update frequency (including time of day and day of week)
    • Pull request limits (per update run and/or open at any time)
    • Automerge options (never/patch/minor, and dev/runtime dependencies)
    • Out-of-range updates (receive only lockfile updates, if desired)
    • Security updates (receive only security updates, if desired)
    dependencies 
    opened by dependabot-preview[bot] 0
  • Correct The README

    Correct The README

    The original code will raise TypeError: The view function did not return a valid response. The return type must be a string, dict, tuple, Response instance, or WSGI callable, but it was a list.

    opened by yeefun 0
  • Race Conditions in Marshmallow - Context Not thread safe?

    Race Conditions in Marshmallow - Context Not thread safe?

    Hello everybody,

    I am having a serious problem. We are serializing a list of objects up to 100 objects at a time/per request and we have some custom field methods.

    In these field methods, we pass the user_id in the context and perform some queries specific to that user_id. Now... I have noticed that sometimes this extra object field is wrong and after much investigation I found out that in some cases (within the list of objects in the same request!) the user_id was wrong and suddenly changed. The user_id passed through the context changed mid serialization of these 100 objects... I checked this "wrong" user and saw that his/her last activity was the same as mine what leads me to the conclusion that for some reason Marshmallow is not thread-safe and there is a race condition? Here is an example of my code:

    # Schema
    class MySchema(SQLAlchemyAutoSchema):
        class Meta:
            model = Object
    
        extra = fields.Method('custom_field', dump_only=True)
    
        def custom_field(self, obj):
            user_id = self.context.get('user_id')
    
            # User Favorites
            favorited = False
            in_favorites = Favorite.query.filter_by(user_id = user_id).first()
            if in_favorites:
                favorited = True
            
            return {
                'user_id' : user_id, 
                'favorited' : favorited
            }
    
    # API
    objects = Object.query.all()
    user = User.query.get(id=id)
    
    many_schema = MySchema(many=True)
    many_schema.context['user_id'] = user.id
    return many_schema.dump(objects)
    

    I am unsure how to proceed now. I would need to fix this as soon as possible.

    Thanks in advance.

    opened by alnikolaj 0
  • How to return MarshalResult when use SQLAlchemyAutoSchema

    How to return MarshalResult when use SQLAlchemyAutoSchema

    when i use schema.dump , i get Python object instead of MarshalResult.

    But the old version, when using find ModelSchema, return MarshalResult.

    How to return MarshalResult when use SQLAlchemyAutoSchema?

    opened by yuruotong1 0
  • Upgrade to GitHub-native Dependabot

    Upgrade to GitHub-native Dependabot

    Dependabot Preview will be shut down on August 3rd, 2021. In order to keep getting Dependabot updates, please merge this PR and migrate to GitHub-native Dependabot before then.

    Dependabot has been fully integrated into GitHub, so you no longer have to install and manage a separate app. This pull request migrates your configuration from Dependabot.com to a config file, using the new syntax. When merged, we'll swap out dependabot-preview (me) for a new dependabot app, and you'll be all set!

    With this change, you'll now use the Dependabot page in GitHub, rather than the Dependabot dashboard, to monitor your version updates, and you'll configure Dependabot through the new config file rather than a UI.

    You have configured automerging on this repository. There is no automerging support in GitHub-native Dependabot, so these settings will not be added to the new config file. Several 3rd-party GitHub Actions and bots can replicate the automerge feature.

    If you've got any questions or feedback for us, please let us know by creating an issue in the dependabot/dependabot-core repository.

    Learn more about migrating to GitHub-native Dependabot

    Please note that regular @dependabot commands do not work on this pull request.

    dependencies 
    opened by dependabot-preview[bot] 1
  • Bump flake8-bugbear from 20.11.1 to 21.4.3

    Bump flake8-bugbear from 20.11.1 to 21.4.3

    Bumps flake8-bugbear from 20.11.1 to 21.4.3.

    Release notes

    Sourced from flake8-bugbear's releases.

    21.4.3

    Verify the element in item_context.args is of type ast.Name for b017

    21.4.2

    • Add another hasattr() check to b017 visit for .func

    21.4.1

    Happy April Fools! This is no joke, it's a real release.

    • Add B017: check for gotta-catch-em-all assertRaises(Exception)

    Catching them all is bad!

    21.3.2

    • Fix crash on tuple expansion in try/except block (#161)

    21.3.1

    • Fix grammar in B015 (#150)
    • Make sure float infinity/NaN does not trigger B008 (#155)
    • Handle positional-only args in class methods (#158)
    Commits
    • 63239e0 Update Change Log for 21.4.3 release
    • 3cab68c Bugfix: Verify the element in item_context.args is of type ast.Name (#166)
    • d3bf9ab Increment version to 21.4.2 for release + Update Changelog
    • a97d3db Add another hasattr() check to b017 visit (#165)
    • bfd3b7e Increment version to 21.4.1 for release
    • 9d18e5f Add B017 - detection for an evil form of assertRaises (#163)
    • e82bb8d Add 21.3.2 changes + increment version for release
    • 8d8d37b Hotfix issue 153 (#161)
    • eb85c48 Increment version to 20.3.1 for release
    • 810fa63 Update changelog for 21.3.1 (#160)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.

    Dependabot will not automatically merge this PR because it includes a major update to a development dependency.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language
    • @dependabot badge me will comment on this PR with code to add a "Dependabot enabled" badge to your readme

    Additionally, you can set the following in your Dependabot dashboard:

    • Update frequency (including time of day and day of week)
    • Pull request limits (per update run and/or open at any time)
    • Automerge options (never/patch/minor, and dev/runtime dependencies)
    • Out-of-range updates (receive only lockfile updates, if desired)
    • Security updates (receive only security updates, if desired)
    dependencies 
    opened by dependabot-preview[bot] 0
  • How to integrate with PickleType

    How to integrate with PickleType

    I want to pass a list to the schema which uses SQLAlchemy's PickleType column. The json file will looks like this:

    json_data = {uuid: '123456...', coords: [[x1, y1], [x2, y2]]}
    

    But looks like ma.SQLAlchemyAutoSchema treat PickleType column as string so if I do schema.load(json_data) it will say coords is not a valid string. I use some trick like str(json_data(coords) before schema.load(json_data) and eval(json_data(coords) after. But when I do schema.dump(model), it will still convert coords to string. And I have to eval it again. Is there better way to to integrate with PickleType? Or is there any way to skip the validation for specific column.

    opened by kaito-albert 0
  • Postgres Money Type

    Postgres Money Type

    I have a sqlalchemy class with a postgres money field budget = db.Column(sqlalchemy.dialects.postgresql.MONEY)

    I'm using the SQLAlchemyAutoSchema to dump a record of containing this, but it is failing with the error decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

    I'm using marshmallow-sqlalchemy 0.23.1 and SQLAlchemy 1.3.15, and as far as I understand it, the MONEY type was added https://github.com/marshmallow-code/marshmallow-sqlalchemy/pull/218

    My completely uneducated guess is that the SQLA_TYPE_MAPPING is just trying to interpret the value as a decimal? However, the value in the query result object is a string, including the currency symbol. e.g. '$800.00'

    opened by Anti-Distinctlyminty 0
  • URLFor and many relationships

    URLFor and many relationships

    I haven't found much luck with the following.

    I'd like to use URLFor to describe a URL for a relationship. I am rendering the child model Lease, which back_populates resources.

    When I am deserializing the Lease object and links is generated, the parent Resource object is desereialized as well, but since it is a list, I am unsure how I can use that relationship to generate a URL to self, which requires looking at lease.relationships[0].discriminator. See LeaseSchema at bottom.

    Resource Model

    class Resource(base_mixin.BaseMixin, db.Base):
        __tablename__ = 'resources'
    
        id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
        name = sqlalchemy.Column(sqlalchemy.String(32), unique=True)
        labels = sqlalchemy.Column(sqlalchemy.dialects.postgresql.JSONB)
    
        lease_id = sqlalchemy.Column(
            sqlalchemy.Integer, sqlalchemy.ForeignKey('leases.id')
        )
        lease = sqlalchemy.orm.relationship('Lease', back_populates='resources')
    
        discriminator = sqlalchemy.Column('type', sqlalchemy.String(50))
    
        __mapper_args__ = {'polymorphic_on': discriminator}
    

    Sapro Model

    class Sapro(resource.Resource):
        __mapper_args__ = {
            'polymorphic_identity': 'sapro',
        }
    
        def __init__(self, *args, **kwargs):
            super(Sapro, self).__init__(*args, **kwargs)
    

    Lease Model

    class Lease(base_mixin.BaseMixin, db.Base):
        __tablename__ = 'leases'
        id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
    
        resources = sqlalchemy.orm.relationship(
            'Resource', back_populates='lease', cascade='all,delete'
        )
    

    Lease Schema

    class LeaseSchema(ma.Schema):
        class Meta:
            fields = (
                'created_at',
                'updated_at',
                'id',
                'resources',
                'links',
            )
    
        resources = marshmallow.fields.Nested(sapro.SaproSchema)
        links = ma.Hyperlinks(
            {
                # Unsure how to pass the discriminator from resources to URLFor.
                #'self': ma.URLFor(
                #    'lease_v1_bp.test_get_leases_by_discriminator',
                #    resources='<resources>',
                #),
                'collection': ma.URLFor('lease_v1_bp.get_leases'),
            }
    
    opened by retr0h 0
  • Allow additional URL parameters to HyperlinkRelated

    Allow additional URL parameters to HyperlinkRelated

    This is basically a reiteration of #54.

    I have an API where a report conceptually has multiple samples. Thus, the sample URL has two parameters, e.g. (my example uses Flask-Restful):

    restful.add_resource(Sample, '/reports/<int:report_id>/samples/<int:sample_id>')
    

    And then the marshmallow schema uses HyperlinkRelated:

    class ReportSchema(ModelSchema):
        samples = ma.List(ma.HyperlinkRelated('rest_api.sample', url_key='sample_id'))
    

    This will then fail with:

    werkzeug.routing.BuildError: Could not build url for endpoint 'rest_api.sample' with values ['sample_id']. Did you forget to specify values ['report_id']?
    

    Notably, this also doesn't work with URLFor(), because that can only take attributes from the parent object, not the relationship objects:

    class ReportSchema(ModelSchema):
        samples = ma.List(ma.URLFor("rest_api.sample", sample_id='<sample_id>', report_id='<report_id>'))
    
    AttributeError: 'sample_id' is not a valid attribute of <Report(21)>
    

    What we need is a dictionary that maps URL parameters to fields on the related object, e.g.

    class ReportSchema(ModelSchema):
        samples = ma.List(ma.HyperlinkRelated('rest_api.sample', url_map={
            'sample_id': 'sample_id',
            'report_id': 'report_id'
        }))
    

    In this case, the url_map field means "fill in the missing segments of the URL by using fields from the relationship object".

    opened by multimeric 1
Owner
marshmallow-code
Python object serialization and deserialization, lightweight and fluffy
marshmallow-code
Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

The Mixer is a helper to generate instances of Django or SQLAlchemy models. It's useful for testing and fixture replacement. Fast and convenient test-

Kirill Klenov 763 Jul 20, 2021
A Flask extension that enables or disables features based on configuration.

Flask FeatureFlags This is a Flask extension that adds feature flagging to your applications. This lets you turn parts of your site on or off based on

Rachel Greenfield 124 Jul 20, 2021
A basic JSON-RPC implementation for your Flask-powered sites

Flask JSON-RPC A basic JSON-RPC implementation for your Flask-powered sites. Some reasons you might want to use: Simple, powerful, flexible and python

Cenobit Technologies 232 Jul 22, 2021
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.3k Jul 24, 2021
Regex Converter for Flask URL Routes

Flask-Reggie Enable Regex Routes within Flask Installation pip install flask-reggie Configuration To enable regex routes within your application from

Rhys Elsmore 47 Jul 8, 2021
🐍 Simple FastAPI template with factory pattern architecture

Description This is a minimalistic and extensible FastAPI template that incorporates factory pattern architecture with divisional folder structure. It

Redowan Delowar 170 Jul 23, 2021
Adds GraphQL support to your Flask application.

Flask-GraphQL Adds GraphQL support to your Flask application. Usage Just use the GraphQLView view from flask_graphql from flask import Flask from flas

GraphQL Python 1.2k Jul 21, 2021
flask extension for integration with the awesome pydantic package

flask extension for integration with the awesome pydantic package

null 141 Jul 17, 2021
Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application.

Flask-Bcrypt Flask-Bcrypt is a Flask extension that provides bcrypt hashing utilities for your application. Due to the recent increased prevelance of

Max Countryman 285 Jul 25, 2021
Qwerkey is a social media platform for connecting and learning more about mechanical keyboards built on React and Redux in the frontend and Flask in the backend on top of a PostgreSQL database.

Flask React Project This is the backend for the Flask React project. Getting started Clone this repository (only this branch) git clone https://github

Peter Mai 21 Jun 20, 2021
Formatting of dates and times in Flask templates using moment.js.

Flask-Moment This extension enhances Jinja2 templates with formatting of dates and times using moment.js. Quick Start Step 1: Initialize the extension

Miguel Grinberg 333 Jul 16, 2021
Pagination support for flask

flask-paginate Pagination support for flask framework (study from will_paginate). It supports several css frameworks. It requires Python2.6+ as string

Lix Xu 234 Jul 2, 2021
CLI and Streamlit applications to create APIs from Excel data files within seconds, using FastAPI

FastAPI-Wrapper CLI & APIness Streamlit App Arvindra Sehmi, Oxford Economics Ltd. | Website | LinkedIn (Updated: 21 April, 2021) fastapi-wrapper is mo

Arvindra 27 Jun 4, 2021
Restful Api developed with Flask using Prometheus and Grafana for monitoring and containerization with Docker :rocket:

Hephaestus ?? In Greek mythology, Hephaestus was either the son of Zeus and Hera or he was Hera's parthenogenous child. ... As a smithing god, Hephaes

Yasser Tahiri 11 Jul 10, 2021