python 2.7至python 3.4错误%不支持的操作数类型:“字节”和“字典” [英] python 2.7 to python 3.4 error unsupported operand type(s) for %: 'bytes' and 'dict'
本文介绍了python 2.7至python 3.4错误%不支持的操作数类型:“字节”和“字典”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从如何从SQLAlchemy表达式中获取原始的,已编译的SQL查询?,在我们从Python 2.7迁移到Python 3.4之前,它一直运行良好。尽管进行了
I got the following code from How do I get a raw, compiled SQL query from a SQLAlchemy expression? and it worked fine until we moved from Python 2.7 to Python 3.4. I've made a few changes though I'm stuck on
return (comp.string.encode(enc) % params).decode(enc)
,错误的错误操作数类型不支持%:'bytes'和'dict'
with the error unsupported operand type(s) for %: 'bytes' and 'dict'
def compile_query(query):
dialect = query.session.bind.dialect
statement = query.statement
comp = compiler.SQLCompiler(dialect, statement)
comp.compile()
enc = dialect.encoding
params = {}
for k,v in comp.params.iteritems():
if isinstance(v, unicode):
v = v.encode(enc)
params[k] = sqlescape(v)
return (comp.string.encode(enc) % params).decode(enc)
推荐答案
感谢评论,我将其移植到python 3
Thanks to the comments, I ported it to python 3
def compile_query(query):
dialect = query.session.bind.dialect
statement = query.statement
comp = compiler.SQLCompiler(dialect, statement)
comp.compile()
enc = dialect.encoding
params = {}
for k,v in comp.params.items():
if isinstance(v, str):
v = v.encode(enc)
params[k] = sqlescape(v)
return (comp.string % params)
这篇关于python 2.7至python 3.4错误%不支持的操作数类型:“字节”和“字典”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文