Coder Social home page Coder Social logo

Comments (12)

SteadBytes avatar SteadBytes commented on June 11, 2024 4

@amickael @apryor6 sorry for the slow response. The flask-restx Flask app setting RESTX_JSON can be used to configure additional parameters for JSON serialisation. Take a look at his and let me know if it works for you πŸ˜„

from datetime import datetime
from json import JSONEncoder

from flask import Flask
from flask_accepts import accepts, responds
from flask_restx import Api, Resource
from marshmallow import Schema, fields


class CustomJSONEncoder(JSONEncoder):
    """Custom encoder for handling default values from a function call"""

    def default(self, o):
        if callable(o):
            return str(o())
        return super().default(o)


app = Flask(__name__)
# Realistically this would be set in a config file
app.config.update(RESTX_JSON={"cls": CustomJSONEncoder})

api = Api(app)

@api.route("/route")
class SomeRoute(Resource):
    @api.doc("some_route")
    @accepts(schema=AcceptSchema, api=api)
    @responds(schema=RespondSchema, api=api)
    def post(self):
        return SomeService.do_stuff(request.parsed_obj)

This setting seems to be completely undocumented so I apologise for that - I'll get it added to the documentation ASAP πŸ‘

from flask_accepts.

amickael avatar amickael commented on June 11, 2024 1

Just looking at a high level (not really sure what's the use case), shouldn't datetime.utcnow be a function call such as in datetime.utcnow()?

No, it’s a callable. If I were to specify utcnow() then all timestamps would default to the time the app was initialized.

from flask_accepts.

ribeirojose avatar ribeirojose commented on June 11, 2024 1

This is probably related to this part of utils.py. I would love to fire a PR this week but I don't have the time right now to get familiar with the code and extensively test this. If this is still open I'd be mostly happy to help down the road. @apryor6 do you think changing that for something like the following would work? I don't really like the fact that we're pre-defining the format, but I think that could be workable as well. With more time we could perhaps make this more generic to comprise other callables, which I think could happen as well in this case. I'm also curious to know more about why map the default attr in marshmallow to the example attr in flask_restx (that's sheer curiosity, I'm not familiar with the implementation of those).

    if hasattr(value, "default") and type(value.default) != ma.utils._Missing:
        fr_field_parameters["example"] = value.default
        if isinstance(value, ma.DateTime):
            fr_field_parameters["example"] = value.default().isoformat()

from flask_accepts.

amickael avatar amickael commented on June 11, 2024 1

Thank you for your help @ribeirojose. This is not urgent at all, I can work around it for now.

from flask_accepts.

ribeirojose avatar ribeirojose commented on June 11, 2024

Just looking at a high level (not really sure what's the use case), shouldn't datetime.utcnow be a function call such as in datetime.utcnow()?

from flask_accepts.

apryor6 avatar apryor6 commented on June 11, 2024

I played around with this a bit using a custom JSON encoder, but it appears that this object is not used in serialization with the Swagger doc creation process.

E.g.

import datetime
import json
from flask.json import JSONEncoder

class CustomJSONEncoder(JSONEncoder):
    """Custom encoder for handling default values from a function call"""

    def default(self, o):
        if callable(o):
            return str(o())
        return super().default(o)

json.dumps(datetime.datetime.utcnow, cls=CustomJSONEncoder)

Works just fine, but if I pass this encoder to the Flask app I still receive the same error you indicated.

app = Flask(__name__)
api = Api(app)
app.json_encoder = CustomJSONEncoder

I think this would require upstream changes to flask-restx unless I am unaware of existing functionality for handling this.

from flask_accepts.

amickael avatar amickael commented on June 11, 2024

Thanks @apryor6, if this requires upstream changes then maybe we close this issue for now? I'll leave it up to you, I can easily work around this in the meantime.

from flask_accepts.

apryor6 avatar apryor6 commented on June 11, 2024

Yeah, I’ve inquired about this with the restx maintainers in their Gitter channel

from flask_accepts.

amickael avatar amickael commented on June 11, 2024

Thanks @SteadBytes! I'll try that out, appreciate the help.

from flask_accepts.

apryor6 avatar apryor6 commented on June 11, 2024

Did this resolve your issue @amickael ?

from flask_accepts.

amickael avatar amickael commented on June 11, 2024

Sorry for the late response @apryor6, that worked perfectly! Thanks everyone.

from flask_accepts.

apryor6 avatar apryor6 commented on June 11, 2024

Wonderful, no worries!

from flask_accepts.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.