def compile_query(query):
    """把一个 sqlalchemy query object 编译成mysql风格的 sql 语句"""
    # from sqlalchemy.sql import compiler
    from sqlalchemy.dialects import mysql as mysql_dialetct
    from pymysql.converters import conversions, escape_item, encoders

    dialect = mysql_dialetct.dialect()
    statement = query.statement
    # comp = compiler.SQLCompiler(dialect, statement, literal_binds=True)
    compile_kwargs = {"render_postcompile": True}
    comp = statement.compile(dialect=dialect, compile_kwargs=compile_kwargs)
    # comp.sql_compile()
    # enc = dialect.encoding
    comp_params = comp.params
    params = []
    for k in comp.positiontup:
        v = comp_params[k]
        if six.PY2 and isinstance(v, six.string_types) and not isinstance(v, six.text_type):
            v = v.decode("utf8")
        v = escape_item(v, conversions, encoders)
        params.append(v)
    return (comp.string % tuple(params))
把一个 sqlalchemy query object 编译成mysql风格的 sql 语句
jqdatasdk/utils.py