Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically convert JSON to Object on Flask Request

In Spring MVC + Jackson (Java), I can have this:

My Object (Java)

public class Project {

   private long id;
   private String self;
   private String key;
   private String name;

   //Getters and Setters
}

Spring MVC Controller

...
@RequestMapping(value="/doSomething", method=RequestMethod.POST)
public String doSomething(@RequestBody Project project) {
    System.out.println(project.getName());
    return "myPage";
}
...

Then, I can send a json like:

{"id": "exampleId", "name": "exampleName","self": "url","key": "key"}

And automatically it converts to my object. On Python, I have my object class. There's something in Flask that I could call:

Flask Controller

@app.route('/doSomething', methods=['POST'])
def do_something(project):
    print project.name
    return "myPage"

My Object (Python)

class Project():

    id=None        
    name=None
    url=None
    key=None

Essentially, I wanna receive my JSON on Flask and already converts to my Object. I wanna avoid from doing this:

class Project(object):
  def __init__(self, id, url, name, key):
    self.id = id
    self.url = url
    self.name = name
    self.key = key
...
import json
my_json = json.loads(request.data)
user = Project(**j)

This way, I'll have to override init from all my objects. Or this:

project = json.loads('{"__type__": "Project", "name": "project", "key": "key"}')
print project['name']
print project['key']

Not good either because it's not my object, it's a dict.

Is this possible? Or I have to choose one of these?

like image 636
Raphael Amoedo Avatar asked Jun 08 '15 19:06

Raphael Amoedo


People also ask

How do I get JSON data from request body in Flask?

You need to set the request content type to application/json for the . json property and . get_json() method (with no arguments) to work as either will produce None otherwise.

How do you use Jsonify in Flask?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.

What is request Get_json ()?

Request. get_json (force=False, silent=False, cache=True)[source] Parses the incoming JSON request data and returns it. By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter.


1 Answers

As far as I know, I don't think you can avoid adding a constructor if you have to use a class in Python.

The other option would be to use namedtuple. They are like tuples but with field names. Either way, you can sort of simulate what you want using a decorator

Ex:

from collections import namedtuple
Project = namedtuple('Project', 'id url name key')

Now you can do something like this in your view handler:

# This decorator takes the class/namedtuple to convert any JSON
# data in incoming request to. 
def convert_input_to(class_):
    def wrap(f):
        def decorator(*args):
            obj = class_(**request.get_json())
            return f(obj)
        return decorator
    return wrap

@app.route('/doSomething', methods=['POST'])
@convert_input_to(Project)
def do_something(project):
    print project.name
    return "myPage"

Also see flask.Request.get_json and make sure 'Content-Type' is set to 'application/json'

like image 177
junnytony Avatar answered Nov 08 '22 20:11

junnytony