python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.17k stars 337 forks source link

Fix: Working outside of request context with marshal_with #361

Open dhanababum opened 3 years ago

dhanababum commented 3 years ago

BEFORE LOGGING AN ISSUE

Code

from flask import Flask
from flask_restx import Api, Resource, fields
from flask_restx.namespace import marshal_with

app = Flask(__name__)
api = Api(app, version='1.0', title='TodoMVC API',
    description='A simple TodoMVC API',
)
todo = api.model('Todo', {
    'id': fields.Integer(readonly=True, description='The task unique identifier'),
    'task': fields.String(required=True, description='The task details')
})

def _marshal():
     return marshal_with(todo)(lambda x: x)

with app.app_context():
      _marhal(**{'task': 'xyz'})

Repro Steps (if applicable)

  1. ...
  2. ...
  3. Broken!

Expected Behavior

Serialize without exception

Actual Behavior

RuntimeError: Working outside of application context.

Error Messages/Stack Trace

RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed to interface with the current application object in some way. To solve this, set up an application context with app.app_context().

https://github.com/python-restx/flask-restx/blob/master/flask_restx/marshalling.py#L251 --> this line is protected by has_app_context https://github.com/python-restx/flask-restx/blob/master/flask_restx/marshalling.py#L252 --> this line is not protected by has_request_context

I have integrated marshal_with serializer to database SQLAlchemy models But getting the RuntimeError: Working outside of request context

Corrected the code and successfully ran tox tests.

Environment

Additional Context

This is your last chance to provide any pertinent details, don't let this opportunity pass you by!

dhanababum commented 3 years ago

360