从谷歌应用引擎连接到远程服务器时Pymongo线程错误

时间:2015-08-29 19:11:46

标签: python mongodb google-app-engine pymongo

我在Google App Engine上部署了Flask应用程序。我正在使用pymongo连接到谷歌计算引擎托管的MongoDB。

这是我的代码:

from pymongo import MongoClient, ASCENDING, DESCENDING

serveraddress = 'my_server_address'
client = MongoClient(serveraddress, 27017)
db = client['MasterData']
MJCollection = db['StoredJsons']
print MJCollection.count()

这会给出一个输出但过程停止:这是错误:

Thread running after request. Creation traceback:
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/runtime.py", line 152, in HandleRequest
    error)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 329, in HandleRequest
    return WsgiRequest(environ, handler_name, url, post_data, error).Handle()
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "/base/data/home/apps/s~appname-frontend/1.386781073242991356/main.py", line 2, in <module>
    from dbHandler import get, update
  File "/base/data/home/apps/s~appname-frontend/1.386781073242991356/dbHandler.py", line 9, in <module>
    client = MongoClient(serveraddress, 27017)
  File "/base/data/home/apps/s~appname-frontend/1.386781073242991356/pymongo/mongo_client.py", line 372, in __init__
    executor.open()
  File "/base/data/home/apps/s~appname-frontend/1.386781073242991356/pymongo/periodic_executor.py", line 64, in open
    thread.start()
  File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/threading.py", line 505, in start
    _start_new_thread(self.__bootstrap, ())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/runtime.py", line 82, in StartNewThread
    return base_start_new_thread(Run, ())

2 个答案:

答案 0 :(得分:0)

恕我直言,这种配置不起作用。 Pymongo MongoClient在连接时会创建一些线程用于监控目的等.GAE不允许这样做。

你在MJCollection.count()而不是在客户端= MongoClient(serveraddress,27017)上获得豁免的原因是,这是MongoClient尝试连接的时间。

您的替代方案是:

  • 使用mongoDB的REST API但是你会受到惩罚 功能和速度。
  • 将您的烧瓶应用程序移至计算引擎

答案 1 :(得分:0)

当我们使用时,PyMongo 2.7曾经在Google App Engine上工作:

serveraddress = 'my_server_address'
client = MongoClient(serveraddress, 27017)
db = client['MasterData']
MJCollection = db['StoredJsons']
print MJCollection.count()

但是对于PyMongo 3.0,我们需要创建一个类,然后为它创建一个对象。

class MongoDB(object):
def __init__(self):
    client = MongoClient(server_address)
    self.db = client[db_name]

def get_collection(self,collection_name):
    return self.db[collection_name]

无论我们想要使用它们,都要创建一个对象并使用它。

如果您遇到任何困难,请告诉我。