今天把django从1.5.5升级到了1.6.2,结果使用mysql-python查询数据库时候就报了这个错误:“not all arguments converted during string formatting”

貌似这个问题应该和django没什么关系,正好今天就看看mysql-python的源码吧。想看如何解决的请直接跳到最后。

查询部分简化后如下:

1
2
3
posistion = "top"
order = r"select id,p_name,p_explain,p_href from pictures where p_position = %s and p_show = 1 order by -id"
self.cur.execute(order, position)

mysql-python中execute函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
del self.messages[:]
db = self._get_db()
if isinstance(query, unicode):
query = query.encode(db.unicode_literal.charset)
if args is not None:
if isinstance(args, dict):
query = query % dict((key, db.literal(item))
for key, item in args.iteritems())
else:
query = query % tuple([db.literal(item) for item in args]) ##########################这里!!
try:
r = None
r = self._query(query)
except TypeError, m:
if m.args[0] in ("not enough arguments for format string",
"not all arguments converted"):
self.messages.append((ProgrammingError, m.args[0]))
self.errorhandler(self, ProgrammingError, m.args[0])
else:
self.messages.append((TypeError, m))
self.errorhandler(self, TypeError, m)
except (SystemExit, KeyboardInterrupt):
raise
except:
exc, value, tb = sys.exc_info()
del tb
self.messages.append((exc, value))
self.errorhandler(self, exc, value)
self._executed = query
if not self._defer_warnings: self._warning_check()
return r

错误地方就是后面加了#的语句。

可以看到,因为字符串也是可序列化的,所以一个字符串被拆分成了单个的字符进行db.literal()处理。这个db是什么呢?

往上找:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def __init__(self, connection):
from weakref import proxy
self.connection = proxy(connection)
self.description = None
self.description_flags = None
self.rowcount = -1
self.arraysize = 1
self._executed = None
self.lastrowid = None
self.messages = []
self.errorhandler = connection.errorhandler
self._result = None
self._warnings = 0
self._info = None
self.rownumber = None
def _get_db(self):
if not self.connection:
self.errorhandler(self, ProgrammingError, "cursor closed")
return self.connection
```
可以看出,这个db就是connection的一个弱引用。再进一步,这个connnection哪来的呢?

```python
def open(self):
""" 返回一个默认的数据库连接游标 """
try:
self.conn = MySQLdb.Connection(
self.db_ip,
self.db_un,
self.db_pd,
self.db_db,
charset=self.db_ch)
self.cur = self.conn.cursor()
except MySQLdb.Error as e:
print e
`

mysqldb-python的connection.py中:

1
2
3
class Connection(_mysql.connection):
"""MySQL Database Connection Object"""
default_cursor = cursors.Cursor

那这个Cursor又是什么呢?

1
2
3
4
class Cursor(CursorStoreResultMixIn, CursorTupleRowsMixIn,
BaseCursor):
"""This is the standard Cursor class that returns rows as tuples
and stores the result set in the client."""

这个Cursor这些类的子类,其中最上面出错函数就是BaseCursor的一个方法。

有点跑偏,先看看那literal函数吧:

1
2
3
4
5
6
7
8
9
10
11
def literal(self, o):
print o,type(o)
print self.encoders
"""
If o is a single object, returns an SQL literal as a string.
If o is a non-string sequence, the items of the sequence are
converted and returned as a sequence.
Non-standard. For internal use; do not use this in your
applications.
"""
return self.escape(o, self.encoders)

print是我添加的,输出如下:

1
2
3
4
5
6
t <type 'str'>
{<type 'instance'>: <function Instance2Str at 0x17b3aa0>, <type 'set'>: <function Set2Str at 0x17b3cf8>, <type 'long'>: <function Thing2Str at 0x17b3de8>, <type 'bool'>: <function Bool2Str at 0x17b3ed8>, <type 'unicode'>: <function unicode_literal at 0x7f12e42c4230>, <type 'str'>: <function string_literal at 0x7f12e42be2a8>, <type 'float'>: <function Float2Str at 0x17b3c08>, <type 'list'>: <function quote_tuple at 0x17b3938>, <type 'tuple'>: <function quote_tuple at 0x17b3938>, <type 'array.array'>: <function array2Str at 0x17b39b0>, <type 'NoneType'>: <function None2NULL at 0x17b3b90>, <type 'datetime.datetime'>: <function DateTime2literal at 0x17b30c8>, <type 'dict'>: <built-in function escape_dict>, <type 'object'>: <function Instance2Str at 0x17b3aa0>, <type 'int'>: <function Thing2Str at 0x17b3de8>, <type 'datetime.timedelta'>: <function DateTimeDelta2literal at 0x17b3140>}
o <type 'str'>
{<type 'instance'>: <function Instance2Str at 0x17b3aa0>, <type 'set'>: <function Set2Str at 0x17b3cf8>, <type 'long'>: <function Thing2Str at 0x17b3de8>, <type 'bool'>: <function Bool2Str at 0x17b3ed8>, <type 'unicode'>: <function unicode_literal at 0x7f12e42c4230>, <type 'str'>: <function string_literal at 0x7f12e42be2a8>, <type 'float'>: <function Float2Str at 0x17b3c08>, <type 'list'>: <function quote_tuple at 0x17b3938>, <type 'tuple'>: <function quote_tuple at 0x17b3938>, <type 'array.array'>: <function array2Str at 0x17b39b0>, <type 'NoneType'>: <function None2NULL at 0x17b3b90>, <type 'datetime.datetime'>: <function DateTime2literal at 0x17b30c8>, <type 'dict'>: <built-in function escape_dict>, <type 'object'>: <function Instance2Str at 0x17b3aa0>, <type 'int'>: <function Thing2Str at 0x17b3de8>, <type 'datetime.timedelta'>: <function DateTimeDelta2literal at 0x17b3140>}
p <type 'str'>
{<type 'instance'>: <function Instance2Str at 0x17b3aa0>, <type 'set'>: <function Set2Str at 0x17b3cf8>, <type 'long'>: <function Thing2Str at 0x17b3de8>, <type 'bool'>: <function Bool2Str at 0x17b3ed8>, <type 'unicode'>: <function unicode_literal at 0x7f12e42c4230>, <type 'str'>: <function string_literal at 0x7f12e42be2a8>, <type 'float'>: <function Float2Str at 0x17b3c08>, <type 'list'>: <function quote_tuple at 0x17b3938>, <type 'tuple'>: <function quote_tuple at 0x17b3938>, <type 'array.array'>: <function array2Str at 0x17b39b0>, <type 'NoneType'>: <function None2NULL at 0x17b3b90>, <type 'datetime.datetime'>: <function DateTime2literal at 0x17b30c8>, <type 'dict'>: <built-in function escape_dict>, <type 'object'>: <function Instance2Str at 0x17b3aa0>, <type 'int'>: <function Thing2Str at 0x17b3de8>, <type 'datetime.timedelta'>: <function DateTimeDelta2literal at 0x17b3140>}

就像上面说的,”top”被拆分成了3个,可是我们语句中的占位符%s只有一个!所以报错 not all arguments converted during string formatting。最初这里我理解成了是哪里转化出了错误,最后醒悟这意思是因为占位符个数和传入参数个数不一样导致!英语不过关阿~不过以前怎么没报错呢??奇怪……

解决办法有2个,简单的方法就是执行语句修改如下:self.cur.execute(order, (position,)) #注意逗号。

更推荐的方法就是使用字典传值:

1
2
3
4
5
if show:
order = r"select id,p_name,p_explain,p_href from pictures where p_position = %(position)s and p_show = 1 order by -id"
else:
order = r"select id,p_name,p_explain,p_href,p_uploaddate,p_show from pictures where p_position = %(position)s"
self.cur.execute(order, {'position': position})

这样虽然多打了几个字母,不过却是一种最稳妥的方式,不用担心由于参数顺序造成错误了。

mysql-python源码写的狠帅阿!

评论和分享

第一种HttpResponse,最基本的返回方式,可以直接返回字符:

1
2
3
from django.http import HttpResponse
def index(request):
return HttpResponse(“a test”)

或者结合contextloder返回网页:

1
2
3
4
5
6
7
from django.template import Context, loader  
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = Context({ 'latest_poll_list': latest_poll_list, })
return HttpResponse(template.render(context))

阅读全文

关于最优价格计算的想法

发布在

假设现在某型号有2个供货商提供,最简化模型如下:

A: (P X),(Q Y)

B: (P M),(Q N)

根据实际情况,买的多价格越低,故X>Y,M>N

如果M>X,N>Y,明显的不论数量多少都应该去A买,反之亦然。

M>X,N<Y为例,则可推断出M>X>Y>N

阅读全文

不知道什么原因,安装kalilinux的时候总是安装失败,失败步骤:安装操作系统。偶尔这步通过了,又出现了grub无法安装的情况。

下载了各个版本都是这样之后,对比了一下sha的值,发现和官网上给出的并不一样….什么情况?!然后根据http://cdimage.kali.org/kali-latest/amd64/这发现,正确的值应该是

1
2
3
4
d859cc2798a24c48ddd37c6aafd88c5dc5e6e123  kali-linux-1.0.6-amd64-mini.iso
281ddb3d14619a973e254b8f484b7fe27defa822 kali-linux-1.0.6-amd64.iso
3cf383be7778d1676c015cb5430422e672ec59fa kali-linux-1.0.6-amd64-mini.torrent
cfa0ad0dce1d4a170adf1cd342c622db23e785ef kali-linux-1.0.6-amd64.torrent

又下载了sha值一样的镜像后,还是无法安装操作系统。

最后发现,如果在磁盘分区时候没选择全放在一起(即第一项推荐新手)而是选择了下面的2项就会导致安装操作系统失败。

真是奇怪的问题….不过总算安装成功了。

评论和分享

使用virtualenv虚拟环境的时候,mysql-python安装时报错:

1
2
3
4
5
_mysql.c:44:23: fatal error: my_config.h: No such file or directory
#include "my_config.h"
^
compilation terminated.
error: command 'gcc' failed with exit status 1

我的系统是fedora20,解决方法就是安装mariadb-devel

如果是ubuntu的话,应该是有个libmysqlclient-dev,安装后就可以在虚拟环境下安装mysql-python了。

评论和分享

最近使用pip安装python模块的时候经常遇到超时而导致失败,解决办法有2个:

  1. 使用-i参数指定url,例如:pip install flask -i http://pypi.v2ex.com/simple
  2. 修改pip的配置文件:
    1
    2
    3
    4
    5
    [global]  
    timeout = 6000
    index-url = http://pypi.v2ex.com/simple
    [install] use-mirrors = true
    mirrors = http://pypi.v2ex.com/

这样就解决了。不过有时候用v2ex的源也超时,这时候使用默认源又好使了……

评论和分享

飞鸟与鱼

发布在 哲理美文

世界上最遥远的距离 The furthest distance way in the world

不是生与死的距离 is not the way from birth to the end.

而是我就站在你面前It is when I stand in front of you

你却不知道我爱你 but you don’t understand I love you.

世界上最遥远的距离 The furthest distance way in the world

不是我就站在你面前 is not when I stand in front of you

你却不知道我爱你 you don’t know I love you

而是爱到痴迷 It is when my love is bewildering the soul

却不能说我爱你 but I can’t speak it out

世界上最遥远的距离 The furthest distance way in the world

不是我不能说我爱你 is not that I can’t say I love you.

而是想你痛彻心脾 It is after missing you deeply into my heart

却只能深埋心底 I only can bury it in my heart

世界上最遥远的距离The furthest distance way in the world

不是我不能说我想你 is not that I can’t say to you I miss you

而是彼此相爱 It is when we are falling in love

却不能够在一起 but we can’t stay nearby

世界上最遥远的距离 The furthest distance way in the world

不是彼此相爱 is not we love each other .

却不能够在一起 but can’t stay together

而是明知道真爱无敌 .It is we know our true love is breaking through the way

却装作毫不在意 we turn a blind eye to it

所以世界上最遥远的距离 So the furthest distance way in the world

不是树与树的距离 is not in two distant trees.

而是同根生长的树枝 It is the same rooted branches

却无法在风中相依 but can’t depend on each other in the wind

世界上最遥远的距离 The furthest distance way in the world

不是树枝无法相依 is not can’t depend on each other in the wind

而是相互瞭望的星星 It is in the blinking stars who only can look with each other

却没有交汇的轨迹 but their trade intersect.

世界上最遥远的距离 The furthest distance way in the world

不是星星没有交汇的轨迹 is not in the blinking stars who only can look with each other

而是纵然轨迹交汇 It is after the intersection

却在转瞬间无处寻觅 but they can’t be found from then on afar

世界上最遥远的距离 The furthest distance way in the world

不是瞬间便无处寻觅 is not the light that is fading away.

而是尚未相遇 It is the coincidence of us

便注定无法相聚 is not supposed for the love.

世界上最遥远的距离 The furthest distance way in the world

是飞鸟与鱼的距离 is the love between the bird and fish.

一个翱翔天际 One is flying in the sky,

一个却深潜海底 the other is looking upon into the sea.

评论和分享

  • 第 1 页 共 1 页
作者的图片

Roy

微信公众号:hi-roy


野生程序猿


China