问题描述
我刚刚学习Google App Engine,并试图找出一种管理与Google Cloud SQL实例的数据库连接的好方法(如果您尚未使用GC-SQL,基本上它就是云中的MySQL,有一些限制)。
我使用python(2.7)GAE环境和webapp2框架来处理请求。我知道常见问题解答表示,建议每次请求都建立到数据库的新连接,但我不知道推荐的关闭连接的方式。每次我在开发过程中尝试删除表时,GC-SQL都会挂起,show processlist显示有一堆进程(可能是因为我没有关闭数据库),并且其中一个进程正在等待一个锁可能是试图删除表的过程)。这很烦人,迫使我重新启动GC-SQL实例(比如重启mysql服务器服务,我想)。也有偶尔的DB打嗝,我认为这与我并没有真正关闭数据库连接有关。
所以,例如,我应该有一个析构函数在我的webapp2.Requesthandler子类实例上断开与数据库的连接? GAE对象有时会被缓存,所以这也是需要考虑的事情。我想我可以连接/查询/断开每个查询,但这似乎并不理想。我知道这是一个模糊的问题,但我希望在这方面玩过的人可以按我的方式给我一些提示。
在此先感谢!
更新:
我尝试在需要cursot的方法中实施一个包装,用谢伊的答案作为出发点。我收到GAE错误。以下是一个特定的新问题: App Engine的Google Cloud SQL有哪些连接限制,以及如何最好地重用DB连接? / a>
我不熟悉Google Cloud SQL,但是不能使用WSGI中间件来打开和关闭连接?
I'm just learning Google App Engine and am trying to figure out a good approach to managing my database connection to a Google Cloud SQL instance (if you haven't used GC-SQL, basically, it's MySQL in the cloud, with a few limitations).
I'm using the python (2.7) GAE environment with the webapp2 framework for handling requests. I know the FAQ says that it's recommended that a new connection to the DB be made with each request, but I don't know what the recommended way of closing the connection is. Each time I try to drop tables during development, the GC-SQL hangs and "show processlist" shows that there are a bunch of processes (likely because I'm not closing the DB) and that one of them is waiting for a lock (likely the process trying to drop the tables). This is annoying and forces me to restart the GC-SQL instance (like restarting mysql-server service, I imagine). There are also occasional DB hiccups that I believe are related to the fact that I'm not really closing my DB connection.
So, for example, should I have a destructor on my webapp2.Requesthandler subclass instance to disconnect from the DB? GAE objects seem to be cached sometimes, so that's also something to consider. I suppose I could just connect/query/disconnect for each query, but this seems suboptimal.
I know this is a vague question, but I'm hoping someone who's played in this area can thow some tips my way.
Thanks in advance!
Update:I tried implementing a wrapper around methods that need a cursot, using Shay's answer as a starting point. I'm getting GAE errors. Here's a new question specific to that: What are the connection limits for Google Cloud SQL from App Engine, and how to best reuse DB connections?
I'm not familiar with Google Cloud SQL, but couldn't you use a WSGI middleware to open and close the connection?
这篇关于在Google Cloud SQL(GAE)Python应用程序中管理数据库连接的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!