-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_poll_db.py
More file actions
126 lines (104 loc) · 4.02 KB
/
create_poll_db.py
File metadata and controls
126 lines (104 loc) · 4.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import sqlite3
import configparser
from datetime import datetime
import uuid
import os
POLL_DB_FILE = 'poll_database.db'
def read_email_list(filename):
try:
with open(filename, 'r') as file:
# Read lines and remove whitespace, empty lines
emails = [line.strip() for line in file if line.strip()]
return emails
except FileNotFoundError:
print(f"Error: File '{filename}' not found.")
exit(1)
except Exception as e:
print(f"Error reading file: {str(e)}")
exit(1)
def create_database():
conn = sqlite3.connect(POLL_DB_FILE)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS polls
(token TEXT PRIMARY KEY,
email TEXT,
vote TEXT,
voted_at DATETIME)''')
conn.commit()
conn.close()
def read_config():
config = configparser.ConfigParser()
config_file = 'config.ini'
if not os.path.exists(config_file):
print(f"Error: Configuration file '{config_file}' not found.")
print("Please ensure config.ini exists in the current directory.")
exit(1)
try:
config.read(config_file)
except Exception as e:
print(f"Error reading configuration file '{config_file}': {str(e)}")
exit(1)
# Validate required sections and variables
required_sections = ['files']
required_vars = {
'files': ['recipients_file']
}
for section in required_sections:
if section not in config:
print(f"Error: Missing required section '[{section}]' in {config_file}")
exit(1)
for var in required_vars[section]:
if var not in config[section]:
print(f"Error: Missing required variable '{var}' in section '[{section}]' of {config_file}")
exit(1)
return config
def check_existing_database():
"""Check if poll database file exists and handle accordingly"""
if os.path.exists(POLL_DB_FILE):
print(f"Warning: Database file '{POLL_DB_FILE}' already exists!")
print("This will delete all existing poll data including any votes that may have been cast.")
while True:
response = input("Do you want to remove the existing database and create a new one? (y/n): ").lower().strip()
if response in ['y', 'yes']:
try:
os.remove(POLL_DB_FILE)
print(f"Existing database '{POLL_DB_FILE}' has been removed.")
return True
except Exception as e:
print(f"Error removing database file: {str(e)}")
exit(1)
elif response in ['n', 'no']:
print("Operation aborted. Existing database preserved.")
exit(0)
else:
print("Please enter 'y' for yes or 'n' for no.")
return True
def initialize_database():
# Read configuration (this will check for config.ini first)
config = read_config()
# Check for existing database and handle accordingly
check_existing_database()
# Get email file path from config
email_file = config['files']['recipients_file']
# Read email addresses from file
print(f"Reading email addresses from {email_file}...")
email_list = read_email_list(email_file)
# Create database if it doesn't exist
create_database()
# Initialize database with email addresses
conn = sqlite3.connect(POLL_DB_FILE)
c = conn.cursor()
try:
for email in email_list:
token = str(uuid.uuid4())
c.execute("INSERT INTO polls (email, token) VALUES (?, ?)",
(email, token))
conn.commit()
print(f"Successfully initialized database with {len(email_list)} email addresses")
except Exception as e:
print(f"Error initializing database: {str(e)}")
conn.rollback()
finally:
conn.close()
if __name__ == "__main__":
initialize_database()