- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我刚刚开始学习 Google App Engine,并且正在尝试找出一种好的方法来管理我的数据库与 Google Cloud SQL 实例的连接(如果您还没有使用过 GC-SQL,基本上,它是云中的 MySQL,有一些限制)。
我使用 python (2.7) GAE 环境和 webapp2 框架来处理请求。我知道常见问题解答说建议对每个请求建立一个到数据库的新连接,但我不知道关闭连接的推荐方法是什么。每次我在开发过程中尝试删除表时,GC-SQL 都会挂起并且“show processlist”显示有一堆进程(可能是因为我没有关闭数据库)并且其中一个正在等待锁(可能是试图删除表的过程)。这很烦人,迫使我重新启动 GC-SQL 实例(就像重新启动 mysql-server 服务一样,我想)。偶尔也会出现数据库问题,我认为这与我没有真正关闭数据库连接这一事实有关。
因此,例如,我是否应该在我的 webapp2.Requesthandler 子类实例上有一个析构函数来断开与数据库的连接? GAE 对象有时似乎被缓存,所以这也是需要考虑的事情。我想我可以为每个查询连接/查询/断开连接,但这似乎不是最佳选择。
我知道这是一个模糊的问题,但我希望在这方面玩过的人能给我一些提示。
提前致谢!
更新:我尝试使用 Shay 的回答作为起点,围绕需要游标的方法实现包装器。我收到 GAE 错误。这是一个特定于此的新问题:What are the connection limits for Google Cloud SQL from App Engine, and how to best reuse DB connections?
最佳答案
这是来自 Getting Started Guide 的 helloworld 示例应用程序的完整示例.它基于来自 Shay Erlichmen 的片段和 JJC ,但这个版本是线程安全的。
你可以这样使用它:
@with_db_cursor(do_commit = True)
def get(self, cursor):
cursor.execute('SELECT guestName, content, entryID FROM entries')
app.yaml
application: helloworld
version: 1
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: helloworld.app
helloworld.py
import cgi
import logging
import os
import threading
import webapp2
from google.appengine.api import rdbms
_INSTANCE_NAME = <name goes here>
def _db_connect():
return rdbms.connect(instance=_INSTANCE_NAME, database='guestbook')
_mydata = threading.local()
def with_db_cursor(do_commit = False):
""" Decorator for managing DB connection by wrapping around web calls.
Stores connections and open cursor count in a threadlocal
between calls. Sets a cursor variable in the wrapped function. Optionally
does a commit. Closes the cursor when wrapped method returns, and closes
the DB connection if there are no outstanding cursors.
If the wrapped method has a keyword argument 'existing_cursor', whose value
is non-False, this wrapper is bypassed, as it is assumed another cursor is
already in force because of an alternate call stack.
"""
def method_wrap(method):
def wrap(self, *args, **kwargs):
if kwargs.get('existing_cursor', False):
# Bypass everything if method called with existing open cursor.
return method(self, None, *args, **kwargs)
if not hasattr(_mydata, 'conn') or not _mydata.conn:
_mydata.conn = _db_connect()
_mydata.ref = 0
_mydata.commit = False
conn = _mydata.conn
_mydata.ref = _mydata.ref + 1
try:
cursor = conn.cursor()
try:
result = method(self, cursor, *args, **kwargs)
if do_commit or _mydata.commit:
_mydata.commit = False
conn.commit()
return result
finally:
cursor.close()
finally:
_mydata.ref = _mydata.ref - 1
if _mydata.ref == 0:
_mydata.conn = None
logging.info('Closing conn')
conn.close()
return wrap
return method_wrap
class MainPage(webapp2.RequestHandler):
@with_db_cursor(do_commit = True)
def get(self, cursor):
cursor.execute('SELECT guestName, content, entryID FROM entries')
self.response.out.write("""
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My Guestbook!</title>
</head>
<body>""")
self.response.out.write("""
<table style="border: 1px solid black">
<tbody>
<tr>
<th width="35%" style="background-color: #CCFFCC; margin: 5px">Name</th>
<th style="background-color: #CCFFCC; margin: 5px">Message</th>
<th style="background-color: #CCFFCC; margin: 5px">ID</th>
</tr>""")
for row in cursor.fetchall():
self.response.out.write('<tr><td>')
self.response.out.write(cgi.escape(row[0]))
self.response.out.write('</td><td>')
self.response.out.write(cgi.escape(row[1]))
self.response.out.write('</td><td>')
self.response.out.write(row[2])
self.response.out.write('</td></tr>')
self.response.out.write("""
</tbody>
</table>
<br /> No more messages!
<br /><strong>Sign the guestbook!</strong>
<form action="/sign" method="post">
<div>First Name: <input type="text" name="fname" style="border: 1px solid black"></div>
<div>Message: <br /><textarea name="content" rows="3" cols="60"></textarea></div>
<div><input type="submit" value="Sign Guestbook"></div>
</form>
</body>
</html>""")
class Guestbook(webapp2.RequestHandler):
@with_db_cursor(do_commit = True)
def post(self, cursor):
fname = self.request.get('fname')
content = self.request.get('content')
# Note that the only format string supported is %s
cursor.execute('INSERT INTO entries (guestName, content) VALUES (%s, %s)', (fname, content))
self.redirect("/")
app = webapp2.WSGIApplication(
[('/', MainPage),
('/sign', Guestbook)],
debug=True)
关于python - 在 Google Cloud SQL (GAE) Python 应用程序中管理数据库连接的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10158805/
这里的这个问题对 updating Google Sheets charts linked to Google slides 有一个简洁的解决方案. function onOpen() { var
我正在尝试将 Google 表单添加到 Google 类作业中,但似乎不可能。 首先,它在这里 ( https://developers.google.com/classroom/reference/
出于某种原因,无论我做什么以及我如何尝试,这个日期格式化程序都不起作用。工具提示仍然显示错误的格式。你可以试试代码here . 在代码中我必须注释掉 formatter.format(dataTabl
我目前正在使用访问 token 和刷新 token 从 Google Analytics Reporting API (v4) 中提取数据。当我致力于自动从 Google Analytics 中提取数
我已在 Google 云端硬盘中创建了一个文件夹,例如测试一下,放入3个文件 a.jpg, b.jpg, c.jpg 我希望在同一帐户下的 Google 电子表格中访问文件,例如生成图像文件的链接,可
电子表格 A 是欢迎新移民来到我们小镇的团队的主数据源。它里面有大量非常敏感的数据,不能公开,哪怕是一点点。 (我们谈论的是 child 的姓名和出生日期以及他们在哪里上学……保证电子表格 A 的安全
有没有办法在 Google 文档中编写 Google Apps 脚本以从 Google 表格中检索仅限于非空白行的范围并将这些行显示为表格? 我正在寻找一个脚本,用于使用 Google Apps 脚本
有没有办法在 Google 文档中编写 Google Apps 脚本以从 Google 表格中检索仅限于非空白行的范围并将这些行显示为表格? 我正在寻找一个脚本,用于使用 Google Apps 脚本
尝试检索存储在 google firebase 中名为条目的节点下的表单条目,并使用谷歌工作表中的脚本编辑器附加到谷歌工作表。 我已将 FirebaseApp 库添加到谷歌表脚本编辑器。然后我的代码看
是否可以将我的 Web 应用程序的登录限制为仅限 google 组中的帐户? 我不希望每个人都可以使用他们的私有(private) gmail 登录,而只能使用我的 google 组中的用户。 最佳答
我们想使用 Google 自定义搜索实现 Google 附加链接搜索框。在谷歌 documentation , 我发现我们需要包含以下代码来启用附加链接搜索框 { "@context"
我想将特定搜索词的 Google 趋势图表添加到我的 Google Data Studio 报告中,但趋势不是数据源列表中的选项。我也找不到嵌入 JavaScript 的选项。是否可以将趋势图表添加到
是否可以将文件从 Google Drive 复制到 Google Cloud Storage?我想它会非常快,因为两者都在类似的存储系统上。 我还没有看到有关无缝执行此操作的任何方法的任何信息,而无需
之间有什么区别 ga('send', 'pageview', { 'dimension1': 'data goes here' }); 和 ga('set', 'dimension1', 'da
我正在尝试记录每个博客站点作者的点击率。 ga('send', 'pageview'); (in the header with the ga code to track each page) ga(
我设置了 Google Tag Manager 和 2 个数据层变量:一个用于跟踪用户 ID,传递给 Google Analytics 以同步用户 session ,另一个用于跟踪访问者类型。 在使用
我在我们的网站上遇到多个职位发布的问题。 我们在加拿大多个地点提供工作机会。所有职位页面都包含一个“LD+JSON ”职位发布的结构化数据,基于 Google 的职位发布文档: https://dev
公司未使用 Google 套件,使用个人(消费者)帐户(甚至是 Google 帐户)违反公司政策。 需要访问 Google Analytics - 没有 Google 帐户是否可能? 谢谢 最佳答案
我想分析人们使用哪些搜索关键字在 Play 商店中找到我的应用。 那可能吗?我怎么能这样做? 最佳答案 自 2013 年 10 月起,您可以关联您的 Google Analytics(分析)和 Goo
Google Now 和 Google Keep 中基于时间和位置的提醒与 Google Calendar 事件提醒不同。是否有公共(public) API 可以访问 Now 和 Keep 中的这些事
我是一名优秀的程序员,十分优秀!