Does Python Flask have a cleaner way to manage mimetypes like Express.js?

Question:

In Express.js I can configure the whole app to support mimetype json or form with this:

app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

Then in the routers, I just get the values with:

function (req, res) {
      fields  =req.body
}

In Flask, I must to use something like this for every route:

if request.mimetype == 'application/json':
   res = request.get_json()
else:
   res = request.form

firstname = res['firstname']
lastname = res['lastname']

but I don’t like using if and else this way. Is there another automatic or cleaner way?

Asked By: stackdave

||

Answers:

Flask got hooks before_request and after_request. You can do your transformation in before_request method.

@app.before_request
def before_request():
    # do your work here
Answered By: Aleksandar Varicak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.