美文网首页
sqlalchemy通过ssh隧道连接mysql

sqlalchemy通过ssh隧道连接mysql

作者: Jlan | 来源:发表于2018-01-30 15:33 被阅读308次
    from sshtunnel import SSHTunnelForwarder
    from sqlalchemy import Column, String, Integer,  DateTime, create_engine
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    
    
    mysql_host = mysql_host
    mysql_port = mysql_port
    mysql_user = mysql_user
    mysql_password = mysql_passwd
    mysql_db = mysql_db
    ssh_host = ssh_host
    ssh_port = ssh_port 
    ssh_user = ssh_user
    ssh_password = ssh_passwd
    
    Base = declarative_base()
    class Behavior(Base):
        __tablename__ = 'user'
        id = Column(Integer, primary_key=True)
        name= Column(String(100))
        gender= Column(String(256))
    
     with SSHTunnelForwarder(
                (ssh_host, ssh_port),  # Remote server IP and SSH port
                ssh_username=ssh_user,
                ssh_password=ssh_passwd,
                remote_bind_address=(mysql_host, mysql_port)
        ) as server:
            server.start()  # start ssh sever
            local_port = str(server.local_bind_port)
            engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(mysql_user,
                                                                                        mysql_passwd,
                                                                                        '127.0.0.1',
                                                                                        local_port,
                                                                                        mysql_db),
                                   pool_recycle=1)
    
            Session = sessionmaker(bind=engine)
            session = Session()
            session.query(User).filter(User.id== 1).all()
    

    相关文章

      网友评论

          本文标题:sqlalchemy通过ssh隧道连接mysql

          本文链接:https://www.haomeiwen.com/subject/xojczxtx.html