render.py 文件源码

python
阅读 23 收藏 0 点赞 0 评论 0

项目:deb-python-sqlalchemy-utils 作者: openstack 项目源码 文件源码
def render_expression(expression, bind, stream=None):
    """Generate a SQL expression from the passed python expression.

    Only the global variable, `engine`, is available for use in the
    expression. Additional local variables may be passed in the context
    parameter.

    Note this function is meant for convenience and protected usage. Do NOT
    blindly pass user input to this function as it uses exec.

    :param bind: A SQLAlchemy engine or bind URL.
    :param stream: Render all DDL operations to the stream.
    """

    # Create a stream if not present.

    if stream is None:
        stream = six.moves.cStringIO()

    engine = create_mock_engine(bind, stream)

    # Navigate the stack and find the calling frame that allows the
    # expression to execuate.

    for frame in inspect.stack()[1:]:
        try:
            frame = frame[0]
            local = dict(frame.f_locals)
            local['engine'] = engine
            six.exec_(expression, frame.f_globals, local)
            break
        except:
            pass
    else:
        raise ValueError('Not a valid python expression', engine)

    return stream
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号