JSONEncoder crashes only in Linux, due to `an unexpected keyword argument 'encoding'`, absent in Windows

Viewed 642

Running the code below in Windows works perfectly, while in Linux (Ubuntu) it's crashing in ThingEncoder.__init__, on the call to super().__init__(*args, **kwargs). The cause of this crash is difference in kwargs.

In Windows, kwargs contains 8 fields:

Windows Fields

While in Linux, it's 18:

enter image description here

The thrown error is :

__init__() got an unexpected keyword argument 'encoding'
[2021-01-04 12:04:31,233] ERROR in app: Exception on /things [GET]
Traceback (most recent call last):
File "/home/me/.local/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
File "/home/me/.local/lib/python3.8/site-packages/flask/app.py", line 1953, in full_dispatch_request
    return self.finalize_request(rv)
File "/home/me/.local/lib/python3.8/site-packages/flask/app.py", line 1968, in finalize_request
    response = self.make_response(rv)
File "/home/me/.local/lib/python3.8/site-packages/flask/app.py", line 2097, in make_response
    raise TypeError(
TypeError: The view function did not return a valid response. The function either returned None or ended without a return statement.
127.0.0.1 - - [04/Jan/2021 12:04:31] "GET /things HTTP/1.1" 500 -

(encoding exists only when running on Linux).

Here is the code:

from flask import jsonify, Flask
from json import JSONEncoder


class ThingEncoder(JSONEncoder):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs) # here is the crash!!
        print("test")

    def default(self, obj):
        # ...some logic...
        return JSONEncoder.default(self, obj)



app = Flask(__name__)
app.json_encoder = ThingEncoder


@app.route('/things', methods=['GET'])
def get_things():
    try:
        jsonify(id=str(7), pt="ZR")
        print("good")
    except Exception as e:
        print(e)


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5432)

Besides crazy hack-works, is there a real solution to it? what's the reason for the different behaviours in Windows/Linux?

Update:

@MacOS's comment below made me question.. and answer: one of the installed packages is responsible for that. A non-necessary one (as it's working without it), that came preinstalled with Python. I still need to pinpoint which one. Hope to update soon...

1 Answers

use flask json

from flask import jsonify, Flask, json

class ThingEncoder(json.JSONEncoder):
    def default(self, obj):
        # ...some logic...
        return JSONEncoder.default(self, obj)
Related