不可序列化的价值

时间:2018-07-04 14:07:01

标签: python serialization flask microservices nameko

我目前遇到序列化问题。在Nameko中,数据似乎可以,但是在Flask中,数据不存在,因为发生了错误。我试图进行序列化和反序列化,但是没有用。

以下是来自MongoDB数据库的数据的示例:

{u'building': u'urk', u'idcapteur': 8, u'room': u'tyu', u'idpiece': 1, u'uri': u'urk/tyu/luminosity/yota1', u'idMesure': 458945, u'subId': u'yota1', u'datemesure2': datetime.datetime(2017, 6, 16, 12, 48, 19, 179000), u'datemesure': datetime.datetime(2017, 6, 16, 12, 48, 19, 179000), u'device': u'luminosity', u'_id': ObjectId('7825ahy'), u'data': {u'date': u'2017-06-16T14:48:19.179435', u'payload': {u'subID': u'yota1', u'input': 50, u'value_units': u'lux', u'value': 500, u'unitID': u'inside'}, u'uri': u'urk/tyu/luminosity/yota1'}, u'mesurevaleur': [{u'idlibv': 5, u'valeur': 500.0}]}

这是我的Nameko程序:

# -*-coding:utf-8 -*

# neocampus.py

import json
from database import startMongoDbConnection, getRawDataCollection, mongoDbQuery
from nameko.rpc import rpc
#from database.py import startMongoDbConnection, getRawDataCollection, mongoDbQuery

mdbConnection = ''
mdbCollection = ''

# Send a request to the microservices system. It will call other microservices
class MsRequest:
    name="msRequest"

    # TODO
    @rpc
    def msRequest(self, value):
        # Connect to MongoDB database and collection, if not already done
        global mdbConnection, mdbCollection, queryResult
        if mdbConnection == '':
            mdbConnection = startMongoDbConnection()
        if mdbCollection == '':
            mdbCollection = getRawDataCollection(mdbConnection)

        # Check the requested microservice
        someData = GetData()
        jsonData = someData.getData(value)

        # It prints the proper data
        for document in jsonData:
            print(document)

        print("FINISHED !!!")

        # Don't forget : closeMongoDbConnection()
        return jsonData

# Get data depending on sensor type
class GetData:
    name="getData"

    def getData(self, sensorType):
        global mdbCollection
        queryResult = mongoDbQuery(mdbCollection, "device", "$eq", sensorType)
        return queryResult


# From database.py


def mongoDbQuery(someCollection, key, choice, value):
    # Use MongoDB query dependeing on choices in parameters
    docs = someCollection.find({key:{choice:value}}).limit(10)

    #for document in docs:
        #print(document)
    return docs

# Start a MongoDB connection
def startMongoDbConnection():
    connected = connectToMongoDb("mongodb")
    return connected

# Start a MongoDB connection
def startMongoDbConnection():
    connected = connectToMongoDb("mongodb")
    return connected

# Choose the first collection available (for raw data)
def getRawDataCollection(connection):
    currentCollection = chooseCollection(connection, mongollection)
    return currentCollection

现在,我的Flask程序:

@app.route('/', methods=['GET', 'POST'])
def getData():
    with ClusterRpcProxy(CONFIG) as rpc:
        myData = rpc.msRequest.msRequest("luminosity")
        #for document in myData:
            #print myData
    return flask.jsonify(**myData)

最后,错误输出:

ERROR in app: Exception on / [GET]
Traceback (most recent call last):
  File "/home/oyo/.local/lib/python2.7/site-packages/flask/app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/oyo/.local/lib/python2.7/site-packages/flask/app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/oyo/.local/lib/python2.7/site-packages/flask/app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/oyo/.local/lib/python2.7/site-packages/flask/app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/oyo/.local/lib/python2.7/site-packages/flask/app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/oyo/flask_sandfox/sandfox.py", line 16, in getData
    myData = rpc.msRequest.msRequest("luminosity")
  File "/home/oyo/.local/lib/python2.7/site-packages/nameko/rpc.py", line 369, in __call__
    return reply.result()
  File "/home/oyo/.local/lib/python2.7/site-packages/nameko/rpc.py", line 327, in result
    raise deserialize(error)
RemoteError: UnserializableValueError Unserializable value: `<pymongo.cursor.Cursor object at 0x7f3274612e50>`

通过打印,数据将正确显示在终端中。但是在Flask中却找不到500。我认为使用JSON数据和Jsonify(可以在此站点找到)可以显示一些内容。但这不是cas。

任何帮助,建议或提示将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

对于有这个确切问题的人,我花了5天的时间找到了它。我确定它是JSON格式的,因为当我复制/粘贴结果时就可以了。实际上,它是在BSON中的(我什至不知道这种格式)。因此,只需将其添加到文件的开头:

from bson.json_util import dumps

然后添加:

# limit for the example
retrievedocs = someCollection.find({* something *}}, {'_id': 0}).limit(10) 
docs = dumps(retrievedocs)

然后,Nameko和Flask之间的序列化将起作用。