eshaan7 / Flask-Shell2HTTP

Execute shell commands via HTTP server (via flask's endpoints).
https://flask-shell2http.readthedocs.io/
BSD 3-Clause "New" or "Revised" License
176 stars 29 forks source link

Nested JSON #27

Closed madhavajay closed 3 years ago

madhavajay commented 3 years ago

I have an issue where the output of my cli tool is JSON but then the nested JSON inside the report field is all messed up and it seems I can't properly json.loads the main result. I wonder if there might be a way to detect json and include it properly rather than escaped inside as a substring?

eshaan7 commented 3 years ago

It's possible to "intercept" the output providing a callback function. See this example.

You should probably be able to write a callback function that does something like:

res: dict = future.result()  # 1. get current result
res["report"] = json.loads(res["report"]) # 2. manipulate report however u want
future._result = res # 3. set new result
eshaan7 commented 3 years ago

🚨 Important!

Because of #31, I would not recommend using callback functions to modify the future's result anymore. So you are left with 2 other options:

  1. Don't change the behavior on flask-shell2http side, handle the JSON parsing on the client side. Shouldn't be too painful IMO.
  2. Use a decorator to modify the JSON response and return the modified response. See below example:
from flask import make_response, jsonify
import functools

def json_parser_decorator(f):
    @functools.wraps(f)
    def decorator(*args, **kwargs):
        response = f(*args, **kwargs)
        resp_json = response.json.copy()
        resp_json["report"] = json.loads(resp_json["report"])
        return make_response(jsonify(resp_json), response.status_code)
    return decorator

shell2http.register_command(
    endpoint="mytool", command_name="mytool", decorators=[json_parser_decorator]
)