0

I'm new to Python and I'm doing some tests with it.

What I need to know is what is the best way of dealing with configuration variables.

For example, for this code:

import twitter
import random
import sqlite3
import time
import bitly_api #https://github.com/bitly/bitly-api-python

class TwitterC:         
    def logtodatabase(self, tweet, timestamp):
        # Will log to the database
        database = sqlite3.connect('database.db') # Create a database file
        cursor   = database.cursor() # Create a cursor
        cursor.execute("CREATE TABLE IF NOT EXISTS twitter(id_tweet INTEGER AUTO_INCREMENT PRIMARY KEY, tweet TEXT, timestamp TEXT);") # Make a table
        # Assign the values for the insert into
        msg_ins       = tweet
        timestamp_ins = timestamp
        values        = [msg_ins, timestamp_ins]
        # Insert data into the table
        cursor.execute("INSERT INTO twitter(tweet, timestamp) VALUES(?, ?)", values)
        database.commit() # Save our changes
        database.close() # Close the connection to the database

In this code, how can I replace 'database.db' with a variable outside of the class, for a better configuration. ?

Best Regards,

3 Answers 3

2

Or you could use argparse if you want to pass in configuration from the command line.

Then when creating the TwitterC class, you could pass in the configuration options you want.

class TwitterC:
    def __init__(self, database):
        self.database = database
    def logtodatabase(self, tweet, timestamp):
        # Will log to the database
        database = sqlite3.connect(self.database) # Create a database file
        #(...)
Sign up to request clarification or add additional context in comments.

Comments

2

You could use ConfigParser out of the Python Standard Library.

Comments

0

You can create a python script that include the configuration variables: config.py:

dbname = 'database.db'
...

your file:

import config
database = sqlite3.connect(config.dbname)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.