python 2.7 to python 3.4 error unsupported operand type(s) for %: 'bytes' and 'dict'

允我心安 提交于 2019-12-12 01:46:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!