2

My problem:

I'm having trouble with a Flask application when it comes to specifying the return type of a function that calls on jsonify() in the return. Flask's jsonify is ultimately returning a current_app.response_class. However, by specifying this type of return in the signature, I get an error.

The error:

Traceback (most recent call last):
  File "wsgi.py", line 1, in <module>
    from app import app as application
  File "./app.py", line 94, in <module>
    def handle_msg_request() -> current_app.response_class:
  File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 348, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/local.py", line 307, in _get_current_object
    return self.__local()
  File "/usr/local/lib/python3.7/site-packages/flask/globals.py", line 51, in _find_app
    raise RuntimeError(_app_ctx_err_msg)
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().  See the
documentation for more information.

The offending code:

from flask import Flask, render_template, request, jsonify, send_from_directory, current_app

@app.route("/requestmessages", methods=['POST'])
def handle_msg_request() -> current_app.response_class:
    last_id = int(request.form['lastId'])
    data = get_all_chat_dict(min=last_id)
    if len(data) == 0:
        return jsonify(hasNewData=False)
    return jsonify(hasNewData=True, dataRows=data)

Related/Similar issue:

I saw how this question had been solved by using with for the context, but I'm not quite sure how I'd apply that here, since I'm just trying to specify the return type for a function.

How can I go about specifying the return type in my signature when this type appears to be intertwined with the application's context?

Joshua Schlichting
  • 3,110
  • 6
  • 28
  • 54

0 Answers0