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

Issue

Express.js allows you to configure your entire app to support MIME type json or forms.

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

app.use(bodyParser.json());
 

Then get the value in the router:

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

In Flask you should use something like this for all routes:

if request.mimetype == 'application/json':
   res = request.get_json()
other than that:
   res = request.form

firstname = res['firstname']
Last Name = res['Last Name']
 

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

Solution

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

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published