Python NeoModel如何将查询结果作为JSON对象

时间:2017-12-27 02:20:58

标签: python flask neo4j flask-restful neomodel

我对Python很新,在我的应用程序中,我使用Neomodel从Neo4j数据库加载和检索图形数据。

在我的一条路线中,我有以下功能:

@api_mod.route('/users')                                                            
def get_users():                                                                                                                                                        
     users = User.nodes #Returns a NodeSet                                                                                                                              
     list_of_users = list(users) #Converts the NodeSet object to a list                                                                                                                                                                                                                                                                    
     return json.dumps(dict(users = [user for user in list_of_users]))    

我的用户类定义如下:

class User(StructuredNode):
    user_id = StringProperty(unique_index=True, required=True)
    logged_in = RelationshipTo('Environment', 'LOGGED_IN', model=LoginAction)
    launched = RelationshipTo('Application', 'LAUNCHED', model=LaunchedAction)
    entered = RelationshipTo('Application', 'ENTERED', model=EnteredAction)
    accessed = RelationshipTo('Application', 'ACCESSED', model=AccessedAction)
    exited = RelationshipTo('Application', 'EXITED', model=ExitedAction)
    logged_out = RelationshipTo('Environment', 'LOGGED_OUT', model=LogoutAction)
    timed_out = RelationshipTo('Environment', 'TIME_OUT', model=TimeoutAction)

    def toJSON(self):
        return dict(user_id = self.user_id)

我的期望是我的/ users路由将返回一个包含数据库中所有用户的JSON对象。我知道NodeSet对象不能序列化为JSON对象,因此我尝试将其转换为列表。但是现在当我运行时,我收到以下错误: " TypeError:类型对象'用户'不是JSON可序列化"

这是整个堆栈跟踪: Traceback(最近一次调用最后一次):   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;, 1997年,致电     return self.wsgi_app(environ,start_response)   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,行1985,在wsgi_app     response = self.handle_exception(e)   在handle_exception中的文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,第1540行     重新加注(exc_type,exc_value,tb)   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/_compat.py" ;,第33行,重新加入     提高价值   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,第1982行,在wsgi_app中     response = self.full_dispatch_request()   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,第1614行,在full_dispatch_request中     rv = self.handle_user_exception(e)   在handle_user_exception中的文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,第1517行     重新加注(exc_type,exc_value,tb)   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/_compat.py" ;,第33行,重新加入     提高价值   文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,第1612行,在full_dispatch_request中     rv = self.dispatch_request()   在dispatch_request中的文件" /Users/mdebarros/.virtualenvs/useractivitylogs/lib/python3.6/site-packages/flask/app.py" ;,第1598行     return self.view_functionsrule.endpoint   文件" /Users/mdebarros/PycharmProjects/useractivitylogs/app/api/routes.py",第16行,在get_users中     return json.dumps(dict(users = [user for list_of_users]中的用户))   文件" /usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/ init .py",第231行,在转储中     return _default_encoder.encode(obj)   文件" /usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" ;,第199行,编码     chunks = self.iterencode(o,_ one_shot = True)   文件" /usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" ;,第257行,在iterencode中     return _iterencode(o,0)   文件" /usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py" ;,第180行,默认情况下     O操作。的即可。的名称) TypeError:类型' User'的对象不是JSON可序列化的

有关如何处理此问题并返回正确的JSON对象的任何帮助或建议?

提前感谢你的帮助。

- MD

1 个答案:

答案 0 :(得分:1)

如您所知,有必要的是,用户类Model有一个方法来执行数据结构的转换过程(序列化),要解决,一个解决方案是添加一个方法来做到这一点:

class User(StructuredNode):
    user_id = StringProperty(unique_index=True, required=True)
    logged_in = RelationshipTo('Environment', 'LOGGED_IN', model=LoginAction)
    launched = RelationshipTo('Application', 'LAUNCHED', model=LaunchedAction)
    entered = RelationshipTo('Application', 'ENTERED', model=EnteredAction)
    accessed = RelationshipTo('Application', 'ACCESSED', model=AccessedAction)
    exited = RelationshipTo('Application', 'EXITED', model=ExitedAction)
    logged_out = RelationshipTo('Environment', 'LOGGED_OUT', model=LogoutAction)
    timed_out = RelationshipTo('Environment', 'TIME_OUT', model=TimeoutAction)

@property
def serialize(self):
    return {
        'user_id': self.user_id,
        'logged_in': self.logged_in,
        'launched': self.launched,
        'entered': self.entered,
        'accessed': self.accessed,
        'exited': self.exited,
        'logged_out': self.logged_out,
        'timed_out'  : self.timed_out
   }

现在,随着方法的添加,属性可以被称为属性:

@api_mod.route('/users')                                                            
def get_users():                                                                                                                                                        
    users = User.nodes                                                                                                                            
    list_of_users = list(users)
    return json.dumps(dict(json_users = [user.serialize for user in list_of_users]))