标签: mysql-python

Mysql + django异常:"命令不同步;你现在无法运行此命令"

通过gunicorn运行django到RDS(AWS mysql),我在gunicorn日志中看到这个错误:

Exception _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in <bound method Cursor.__del__ of <MySQLdb.cursors.Cursor object at 0x690ecd0>> ignored
Run Code Online (Sandbox Code Playgroud)

我还不能可靠地重现它,也无法追踪导致它的底层代码.

我在某些地方使用原始游标,遵循以下模式:

cursor = connections['read_only'].cursor()
sql = "select username from auth_user;"
cursor.execute(sql)
rows = cursor.fetchall()
usernames = []
for row in rows:
    usernames.append(row[0])
Run Code Online (Sandbox Code Playgroud)

在某些地方,我立即将光标重用于另一个查询execute()/ fetchall()模式.有时我没有.

我还在某些地方使用原始管理器查询.

我没有明确关闭游标,但我不相信我应该.

除此之外:我没有使用任何存储过程,没有init_command参数,也没有在我在这里发布的其他答案中指出的任何其他内容.

任何有关如何调试的想法或建议将不胜感激.

mysql django mysql-python amazon-rds

6
推荐指数
1
解决办法
3203
查看次数

在python中安装MySQLdb

我在windows中安装了3.3.0 python安装程序.然后我想安装MySQLdb.我在安装文件中搜索python 3.3.0,我得到了"MySQL-python-1.2.4b4.win32-py2.7"并安装了它.但它显示'需要python版本2.7,这在您的注册表中找不到'.我也在stackoverflow中得到了关于这个问题的解决方案,但我的问题没有解决.我试过的内容解释如下:

1. First I have exported python from registry HKEY_LOCAL_MACHINE-> Software.
2. I have saved the file in desktop.
3. I open it with notepad++.
4. Then I replaced all the LOCAL_MACHINE with CURRENT_USER and save it.
5. Finally  I executed the saved file in desktop.
Run Code Online (Sandbox Code Playgroud)

但没有任何事情发生,我的问题没有解决,就像以前一样.它有什么解决方案吗?

mysql-python

6
推荐指数
1
解决办法
2538
查看次数

Django Rest Framework/Django性能问题

我目前正在我的EC2小型实例服务器上部署Django w/Django-Rest-Framework,为几个Android应用程序提供一组API.

问题是我遇到了一个严重的性能问题,我不得不介绍一下.我发现单个请求的大部分时间都花在了DRF的核心内部.

很抱歉让这篇文章很长,但我想我必须展示一切,这样我才能得到正确的答案.让我继续吧:

我的设置是nginx/uwsgi.以下是我使用upstart运行uwsgi的方法:

description "pycms"
start on [2345]
stop on [06]

respawn

# start from virtualenv path
chdir /www/python/apps/pycms/

exec uwsgi -b 25000 --chdir=/www/python/apps/pycms --module=wsgi:application --env DJANGO_SETTINGS_MODULE=settings --socket=127.0.0.1:8081 --processes=5  --harakiri=20  --max-requests=5000  --vacuum --master --pidfile=/tmp/pycms-master.pid 
Run Code Online (Sandbox Code Playgroud)

假设我请求以下API:

http://IP_ADDRESS/api/nodes/mostviewed/9/
Run Code Online (Sandbox Code Playgroud)

符合以下规则:

url(r'^nodes/mostviewed/(?P<category>\d+)/$', MostViewedNodesList.as_view(), name='mostviewed-nodes-list'),
Run Code Online (Sandbox Code Playgroud)

这是基于类的视图:

class MostViewedNodesList(generics.ListAPIView):
    """
    API endpoint that lists featured nodes
    """
    model = ObjectStats
    serializer_class = NodeSerializer
    permission_classes = (permissions.AllowAny,)

    def get_queryset(self):
        if(self.kwargs.has_key('category')):
            category_id = self.kwargs.get('category')
            return ObjectStats.get_most_viewed(category_id)
        else:
            return []
Run Code Online (Sandbox Code Playgroud)

序列化程序类:

class NodeSerializer(serializers.ModelSerializer):
    images = ImageSerializer()
    favorite …
Run Code Online (Sandbox Code Playgroud)

python django profiling mysql-python django-rest-framework

6
推荐指数
1
解决办法
4648
查看次数

如何在数据库中存储实时聊天消息?

我mysqldb目前正在使用我的数据库,我需要集成一个实时的消息传递功能.在chat demo那个龙卷风提供不实现数据库,(而blog 做.)

此消息传递服务也将在未来兼作电子邮件(如Facebook的消息服务如何工作.聊天平台也是电子邮件.)无论如何,我想确保我当前的第一个聊天版本能够扩展作为电子邮件,总的来说,我需要将消息存储在数据库中.

这样的事情很简单:对于发送的每条聊天消息,查询数据库并在用户屏幕上显示消息.或者,这种方法是否容易受到高服务器负载和不良优化的影响?我应该如何构建"基础设施"以使其工作?

(我为这个问题中的一些固有的主观性道歉;但是,我更喜欢"测量两次,代码一次.")

输入,示例和资源受到赞赏.
问候.

python chat real-time tornado mysql-python

6
推荐指数
1
解决办法
2080
查看次数

MySQL在一个查询中选择并更新

我正在尝试从MySQL(total_points)中选择一个值,然后添加到局部变量(new_points)并更新SAME查询中的total_points,是否有人知道这是否可能...

我现在有.,

cursor = database.cursor() 
cursor.execute("""SELECT total_points FROM g_ent WHERE e_id =%s AND user =%s;
UPDATE total_points = (total_points + %s)"""
,(e_id, user_name, new_points))
database.commit()    
Run Code Online (Sandbox Code Playgroud)

mysql mysql-python

6
推荐指数
1
解决办法
1万
查看次数

与从CSV文件导出和导入相比,Python MySQLdb SScursor速度较慢.加速可能吗?

作为构建数据仓库的一部分,我必须查询源数据库表大约75M行.

我想对75M行做什么是一些处理,然后将结果添加到另一个数据库.现在,这是非常多的数据,我主要采用两种方法取得了成功:

1)使用MySQL的"SELECT ... INTO"功能将查询导出到CSV文件,并使用python的fileinput模块读取它,

2)使用MySQLdb的SScursor连接MySQL数据库(默认光标将查询放入内存,查杀python脚本)并以大约10k行的块结果获取结果(这是我发现最快的块大小) ).

第一种方法是"手动"执行的SQL查询(大约需要6分钟),然后是读取csv文件并处理它的python脚本.我使用fileinput读取文件的原因是fileinput从一开始就没有将整个文件加载到内存中,并且适用于较大的文件.只需遍历文件(读取文件中的每一行并调用pass)大约需要80秒,即1M行/秒.

第二种方法是执行相同查询的python脚本(也需要大约6分钟,或稍长一些),然后只要在SScursor中有任何左边,就会循环获取行的块.在这里,只需读取行(一个接一个地取出一个块而不做其他任何操作)大约需要15分钟,或大约85k行/秒.

The two numbers (rows/s) above are perhaps not really comparable, but when benchmarking the two approaches in my application, the first one takes about 20 minutes (of which about five is MySQL dumping into a CSV file), and the second one takes about 35 minutes (of which about five minutes is the query being executed). This means that dumping and reading to/from a CSV file is about twice as fast as …

python mysql csv file-io mysql-python

6
推荐指数
1
解决办法
771
查看次数

如何在Python 2.6 CentOS中安装MySQLdb

我yum install mysql-python用来安装MySQLdb 时收到此消息.

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.sin3.sg.voxel.net
 * extras: mirrors.sin3.sg.voxel.net
 * updates: mirrors.sin3.sg.voxel.net
base                                                      | 3.7 kB     00:00
extras                                                    | 3.4 kB     00:00
updates                                                   | 3.4 kB     00:00
Setting up Install Process
No package mysql-python available.
Error: Nothing to do
Run Code Online (Sandbox Code Playgroud)

更新
结果yum repolist

root@server [~]# yum repolist
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.sin3.sg.voxel.net
 * extras: mirrors.sin3.sg.voxel.net
 * updates: mirrors.sin3.sg.voxel.net
base                                     | 3.7 …
Run Code Online (Sandbox Code Playgroud)

python centos mysql-python

6
推荐指数
1
解决办法
3万
查看次数

无法在App Engine上捕获MySQLdb.OperationalError

我在Google App Engine上运行了一个Django应用程序.DB不时会引发OperationalError正常情况,但是我的代码虽然使用了try..except,却没有捕获异常(我需要这个用于重试目的).

这是我的代码:

from MySQLdb import OperationalError, DatabaseError

DB_RETRY_EXCEPTIONS = (
    OperationalError,
    DatabaseError,
)

class MyClassView(rest_framework.views.APIView):
    @retry(DB_RETRY_EXCEPTIONS, tries=5, delay=5, logger=logger)
    def dispatch(self, *args, **kwargs):
        try:
            return super(MyClassView, self).dispatch(*args, **kwargs)
        except DB_RETRY_EXCEPTIONS as exp:
            logger.warning("Got %s", exp)
            raise
Run Code Online (Sandbox Code Playgroud)

在异常堆栈跟踪中,我可以看到流程正在通过这段代码,但没有警告.

这是堆栈跟踪的最后几行:

File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/MySQLdb-1.2.4b4/MySQLdb/__init__.py", line 81, in Connect
    return Connection(*args, **kwargs)
File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/MySQLdb-1.2.4b4/MySQLdb/connections.py", line 190, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 38")
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.

python mysql django google-app-engine mysql-python

6
推荐指数
1
解决办法
1500
查看次数

TypeError:+:'decimal'和'float'不支持的操作数类型

我使用的是Python 2.7和MySQLdb.我在这段代码上得到了这个错误:

Value = 5
x.execute("SELECT number from Testing where id ='%s';" % Value)
data = x.fetchall()
print (data)
data = data[0][0]
data = data + 0.5
x.execute(""" UPDATE Testing SET number = %s WHERE id = %s """, (data, Value))
conn.commit()
Run Code Online (Sandbox Code Playgroud)

错误发生在该行:data = data + 0.5.

TypeError: unsupported operand type(s) for +: 'decimal' and 'float'.

这个数字是DECIMAL(8,1).我已经看到了此错误的其他问题,但没有添加.另外,我认为如果他们不熟悉Python并且无法理解类似问题的更高级Python编码,那么有些人会遇到同样的问题.请你帮助我好吗?提前致谢.

python mysql decimal typeerror mysql-python

6
推荐指数
1
解决办法
9883
查看次数

如何在mysql/mariaDB中的JSON列上执行SELECT

如何在JSON列上应用WHERE子句以对具有两列(id Integer,attr JSON)的表执行SELECT查询.JSON是嵌套的,在过滤条件中,只允许有一个json键值对.这个关键值对可以在Josn的任何地方.

+----+-----------------------------------------------------------------
| id | attr                                                                                          
|
+----+-----------------------------------------------------------------
|  1 | {"id":"0001","type":"donut","name":"Cake","ppu":0.55}                                         
|
|  2 | {"id":"0002","type":"donut","name":"Cake","ppu":0.55,"batters":
       {"batter1":100,"batter2":200}} 
+----+-----------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

mysql mysql-python mariadb

6
推荐指数
2
解决办法
1万
查看次数