connect.py 1.2 KB

1234567891011121314151617181920212223242526272829
  1. import psycopg2 as pg
  2. from sshtunnel import SSHTunnelForwarder
  3. from BackendApi.config import SSH_H, host, user, db_name, password
  4. def connect():
  5. try:
  6. print('Connecting to the PostgreSQL Database...')
  7. # подключение по ssh к серверу
  8. ssh_tunnel = SSHTunnelForwarder(
  9. (SSH_H, 334), #ip address and port
  10. ssh_username="evgeny_polivanov", #имя пользователя
  11. ssh_private_key= 'D:/sshc',# путь к файлу где расположен ssh ключ (не .pub)
  12. ssh_private_key_password= '',# пароль (в данном случае пароль отсутствует)
  13. remote_bind_address=(host, 5432) # не особо понял что это
  14. )
  15. ssh_tunnel.start()
  16. print("Tunnel start!")
  17. # Подключение к базе данных
  18. conn = pg.connect(
  19. host=host,
  20. port=ssh_tunnel.local_bind_port,
  21. user=user,
  22. password= password,
  23. database=db_name
  24. )
  25. print("Success database connect!")
  26. return conn
  27. except:
  28. print('Connection Has Failed...')