[英]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.我想将用户定义的 object 参数传递给我的 flask 应用程序发布方法,我的意思是序列化应该在客户端完成并在服务器自动反序列化。 eg: I have a Student class:
例如:我有一个学生 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:我的 flask 应用程序是:
@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?有什么办法让我输入一个用户定义的对象(学生类),然后可以序列化并传输到flask应用程序,flask应用程序可以反序列化吗?
I know I could post a json object at client by specifying the content-type:我知道我可以通过指定内容类型在客户端发布 json object:
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:并通过 get_json 方法获取 json object,如下所示:
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?并在 flask 应用服务器上解析这个 object,但我想找到一些更 Python 的方法来做到这一点,就像我在问题中提到的那样,有什么办法吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.