Search code examples
pythonjsonformspostcherrypy

CherryPy JSON vs Form POST


I have a web application developed in Python with the CherryPy framework. It uses many conventional HTML forms (with x-www-form-urlencoded data).

I'm developing an iOS application that I want to sync with the same database that the web application uses. To upload from iOS to the database I want to upload JSON in the HTTP request body with the HTTP POST method.

I tried writing a method in my web application to process the uploaded JSON data.

If my cherrypy.config looks like this

cherrypy.config.update({
    'environment': 'production',
    'log.screen': False,
    'log.access_file': '/home/adamek/webapps/cocoa_foody/logs/access.log',
    'log.error_file': '/home/adamek/webapps/cocoa_foody/logs/error.log',
    'server.socket_host': '127.0.0.1',
    'server.socket_port': 15982,
    'tools.caching.on': False,
    'tools.encode.encoding': "utf-8",
    'tools.json_in.on': True,
})

my JSON pages work, but form submissions from the rest of my web application fail.

If I change the last line to 'tools.json_in.on': False, My old form pages work again, but the JSON POST pages fail (cherrypy.request.json is None).

The requests to the JSON pages have Content-Type: application/json in the request headers.

The request to the other form pages have 'Content-Type: application/x-www-form-urlencoded '

Is there any way to have one CherryPy application handle both application/json and application/x-www-form-urlencoded, or do I need to have two separate CherryPy applications?


Solution

  • Found it! Just needed to add 'tools.json_in.force': False, to the config.

    cherrypy.config.update({
    'environment': 'production',
    'log.screen': False,
    'log.access_file': '/home/adamek/webapps/cocoa_foody/logs/access.log',
    'log.error_file': '/home/adamek/webapps/cocoa_foody/logs/error.log',
    'server.socket_host': '127.0.0.1',
    'server.socket_port': 15982,
    'tools.caching.on': False,
    'tools.encode.encoding': "utf-8",
    'tools.json_in.on': True,
    'tools.json_in.force': False,
    })