问题
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)
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)
回答1:
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)
来源:https://stackoverflow.com/questions/28227190/python-2-7-to-python-3-4-error-unsupported-operand-types-for-bytes-and-d