Comments (12)
@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.
Just looking at a high level (not really sure what's the use case), shouldn't
datetime.utcnow
be a function call such as indatetime.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.
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.
Thank you for your help @ribeirojose. This is not urgent at all, I can work around it for now.
from flask_accepts.
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.
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.
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.
Yeah, Iβve inquired about this with the restx maintainers in their Gitter channel
from flask_accepts.
Thanks @SteadBytes! I'll try that out, appreciate the help.
from flask_accepts.
Did this resolve your issue @amickael ?
from flask_accepts.
Sorry for the late response @apryor6, that worked perfectly! Thanks everyone.
from flask_accepts.
Wonderful, no worries!
from flask_accepts.
Related Issues (20)
- When using the @responds decorator, X-Fields headers are automatically applied to the swagger request HOT 2
- Swagger fails to load when a schema does not have a default set in one of the fields. HOT 4
- Marshmallow schema for form data HOT 1
- Query parameter and header schemas do not respect the data key attribute HOT 1
- Passing a schema type to the `schema` argument of @accepts ignores the type's Meta attributes
- Marshmallow 4 breaking changes
- Overriding flask_restx field
- Nested Marshmallow Schemas throwing error on Swagger HOT 5
- Partial param for Schema loading HOT 4
- [Q] Customize schema_errors? HOT 2
- Only swagger generation for end-point HOT 10
- What is the best practice for file uploads? HOT 2
- Working with UUIDs, Marshmallow & 'missing' fields
- Nested schemas with many=true do not generate a list of schemas in the swagger docs HOT 6
- The new partial keyword of accepts() breaks the marshmallow schema
- Using multiple different schemas in accepts decorator raises KeyError if there is a ValidationError
- Cookie header validation works on gunicorn, does not on NGINX
- Static typing on request.parsed_obj
- More forgiving loading of the JSON schema payload ignoring the mimetype
- Skip response fields where value is None
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 flask_accepts.