Reputation: 25554
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,
Upvotes: 0
Views: 1747
Reputation:
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)
Upvotes: 0
Reputation: 2605
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
#(...)
Upvotes: 2
Reputation: 4557
You could use ConfigParser out of the Python Standard Library.
Upvotes: 2