import my database connection with python

It is possible, but it's not good idea to mix code and data (any kind - configuration, HTML etc), for at least two reasons:

  • Design - you end up with so called high coupling. Situation where there is a lot of dependencies, hard to follow, and your app is more and more difficult to modify.
  • Security - your credentials sooner or later end up in some code backup archive or repository. Config file can be additionally encrypted, py file not really. If it's a web app, it's easier to restrict access to single config file then to all py files that can have sensitive data.

You can still create this separate, easy to use, connection handling function. But move your connection credentials to separate configuration file.

config.ini:

[mysqlDB]
host = '0.0.0.0'
db = 'test'
user = 'root'
pass = 'pswd'

You can read configuration in your connection py file or make it more global (ie singleton?). If you want to read configuration in connection file:

storage.py:

import configparser
import MySQLdb.cursors

config = configparser.ConfigParser()
config.read('config.ini')

def connect():
    return MySQLdb.connect(host = config['mysqlDB']['host'],
                           user = config['mysqlDB']['user'],
                           passwd = config['mysqlDB']['pass'],
                           db = config['mysqlDB']['db'])

Usage example:

import storage

conn = storage.connect()

Tags:

Python

Mysql