sshtunnel 建立数据库通道连接

with SSHTunnelForwarder((settings.ssh_host, settings.ssh_port),
                        ssh_password=settings.ssh_password, ssh_username=settings.ssh_username,
                        remote_bind_address=(settings.host, settings.port)) as server:

    conn = psycopg2.connect(
        host='localhost',
        port=server.local_bind_port,
        database=settings.database,
        user=settings.user,
        password=settings.password
    )
    cursor = conn.cursor()
    sql = '''
            insert into trend(
                    new_listings,homes_sold,average_days_on_market,selling_to_listing_price_ratio,city,"createdDate")
                     values(72,30,32,0.96,'East Gwillimbury',now())
        '''
    cursor.execute(sql)
    conn.commit()
    return 'successful'

关于以前这个程序无法在外面引用conn,但是函数里面就能使用conn的问题:

今天终于知道了,就是 with as 这个上下文管理器,太坑了;

你可以通过返回一个函数的形式让这个上下文管理器不关闭继续使用:如:return query_fn(conn)

但是如果你直接return conn 这时候,ssh隧道连接已经关闭了,conn已经没有作用了;

猜你喜欢

转载自blog.csdn.net/weixin_38859557/article/details/84999907