所以我为我的后端设置了这个设置,Python 处理数据挖掘并与数据库通信(MongoDB 通过 PyMongo),Node.js/Restify 通过 ZeroRPC 调用 Python 方法。
我有以下类,其功能如下:
Importer
- 将数据从 csv 导入、转换和清理为 json 数据。Database
- 数据库对象,包含 MongoClient 并处理从Importer
.Analytics
- 包含数据挖掘方法的对象;要传递给zerorpc.Server
. 需要传递一个实例或Database
类来访问数据库。
所以这就是我的app.py
样子。
import os
import zerorpc
from scripts.database import Database
from scripts.importer import Importer
from scripts.analytics import Analytics
from utils.timer import time_function
ROOT = os.path.dirname(__file__)
if __name__ == "__main__":
importer = Importer()
db = Database(data=importer.data)
services = Analytics(db)
server = zerorpc.Server(services)
server.bind("tcp://0.0.0.0:1234")
server.run()
然而它显示了这个错误:
Traceback (most recent call last):
File "D:/Projects/Dashboards/app/app.py", line 28, in <module>
server = zerorpc.Server(Analytics())
File "D:\Projects\Dashboards\env\lib\site-packages\zerorpc\core.py", line 292, in __init__
pool_size, heartbeat)
File "D:\Projects\Dashboards\env\lib\site-packages\zerorpc\core.py", line 72, in __init__
self._methods[k] = rep(functor)
File "D:\Projects\Dashboards\env\lib\site-packages\zerorpc\decorators.py", line 36, in __init__
self.__name__ = functor.__name__
File "D:\Projects\Dashboards\env\lib\site-packages\pymongo\collection.py", line 262, in __getattr__
name, full_name, full_name))
AttributeError: Collection has no attribute '__name__'. To access the sales.__name__ collection, use database['sales.__name__'].
Process finished with exit code 1
所以此时我意识到,“可能是因为我传递了对象的一个实例,而不是对象本身。”
所以我把我的Analytics
变成了这个:
from bson.son import SON
import datetime
class Analytics(object):
# def __init__(self, database):
# self.db = database.db
# self.sales = database.tb_sales
@classmethod
def connect_db(cls, database):
cls.db = database.db
cls.sales = database.tb_sales
...other methods here...
类方法connect_db
曾经__init__
是Analytics
. 因此我app.py
的更改为:
import os
import zerorpc
from scripts.database import Database
from scripts.importer import Importer
from scripts.analytics import Analytics
from utils.timer import time_function
ROOT = os.path.dirname(__file__)
if __name__ == "__main__":
importer = Importer()
db = Database(data=importer.data)
Analytics.connect_db(database=db)
server = zerorpc.Server(Analytics())
server.bind("tcp://0.0.0.0:1234")
server.run()
但它仍然显示相同的错误。
这是为什么?有任何想法吗?不知何故,我认为它zerorpc
与获取函数的性质有关__name__
,以便客户端可以调用它?只是我的两分钱。