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.16k stars 335 forks source link

Returning an object on 404 #550

Closed denisvitez closed 1 year ago

denisvitez commented 1 year ago

Hello,

in my app, I'm always returning an object (dict) for all 4xx status messages. Since my URL is structured as /controller/entity_id/action I abort for 404, when the entity for the given id is not found in the system. The problem is that for 404 responses this doesn't work, since the library tries to add similar URLs matches to the message, but since my message is actually an object (dict) this causes an exception to occur.

'dict' object has no attribute 'rstrip'

# _help_on_404
close_matches = difflib.get_close_matches(request.path, rules.keys())
if close_matches:
    # If we already have a message, add punctuation and continue it.
    message = "".join(
        (
            (message.rstrip(".") + ". ") if message else "", # this line causes the exception...
            "You have requested this URI [",
            request.path,
            "] but did you mean ",
            " or ".join((rules[match] for match in close_matches)),
            " ?",

Does anyone know if it's possible to disable these close matches search and automatic message extensions when performing a 404 abort, or in general?

peter-doggart commented 1 year ago

You should be able to disable the automatic 404 help behaviour by setting the RESTX_ERROR_404_HELP config flag to False:

app = Flask(__name__)
app.config['RESTX_ERROR_404_HELP'] = False
denisvitez commented 1 year ago

Thank you @peter-doggart this indeed works as advertised :)

MajorDallas commented 10 months ago

While it's great that this behavior can be disabled if needed, since this code path executes when using flask.abort and the example usage of flask.abort shows it being passed a flask.Response, I feel the best thing to do would be to make _help_on_404 support at least that type.