简体   繁体   中英

How to pass a user defined object parameter to flask post method?

I would like to pass a user defined object parameter to my flask app post method, I mean the serialization should be done at client and deserialization at server automatically. eg: I have a Student class:

class Student(object):
    def __init(self, name, age, sno):
         self.name = name
         self.age = age
         self.sno = sno

    def __repr(self):
        return 'Student [name: %s, age: %d, sno: %d]' % (self.name, self.age, self.sno)

And my flask app is:

@route('/addstudent', method=['post'])
def add_student():
    stu = request.some_function() # some_function should get a Student object from request and deserialize it autimatically
    if not isinstance(stu, Student):
        return 'input is not a Student object.'
    return do_something(stu)

Is there any way to let me input a user defined object(Student class), then it can be serialized and transferred to flask app, and the flask app can deserialized it?

I know I could post a json object at client by specifying the content-type:

request_body = '{"name": "tom","age": 20, "sno": 12}'
request_header = {'Content-Type': 'application/json'}

And getting a json object by the get_json method like below:

stu = request.get_json()

And parsing this object at flask app server, but I would like to find some more pythonic way to do this, just like what I metioned in the question, is there any way?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM