Skip to content

Commit 7313c75

Browse files
authoredSep 30, 2017
Create handlers.py
1 parent f69666f commit 7313c75

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
 

‎handlers.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import sqlite3
2+
import smtplib
3+
4+
class UserError(Exception):
5+
pass
6+
7+
class SqlHandler:
8+
def __init__(self):
9+
self.connection = sqlite3.connect("comments.db")
10+
self.cursor = self.connection
11+
12+
cmd = """
13+
CREATE TABLE IF NOT EXISTS users (
14+
id INTEGER PRIMARY KEY,
15+
username TEXT
16+
email TEXT
17+
password TEXT);"""
18+
19+
self.cursor.execute(cmd)
20+
21+
cmd = """
22+
CREATE TABLE IF NOT EXISTS comments (
23+
id INTEGER PRIMARY KEY,
24+
senderId INTEGER
25+
comment TEXT);"""
26+
27+
self.cursor.execute(cmd)
28+
29+
def login(self, username, password):
30+
cmd = "SELECT 1 FROM users WHERE ((username = {0} OR email = {0}) AND password = {1});".format(username, password)
31+
self.cursor.execute(cmd)
32+
user = self.cursor.fetchone()
33+
try:
34+
assert user != None
35+
except AssertionError:
36+
raise UserError("While logging in: Username or password not correct.")
37+
return user
38+
39+
def signup(self, username, email, password):
40+
cmd = "SELECT 1 FROM users WHERE (username = \"{0}\" OR email = \"{1}\");".format(username, email)
41+
self.cursor.execute(cmd)
42+
try:
43+
assert user == None
44+
except AssertionError:
45+
raise UserError("While signing up: User with username or email already exists")
46+
return False
47+
cmd = "INSERT INTO users VALUES(NULL, {0}, {1}, {2});\n SELECT 1 FROM users WHERE (username = {0});".format(username, email, password)
48+
self.cursor.execute(cmd)
49+
return self.cursor.fetchone()
50+
51+
def sendComment(self, senderId, comment):
52+
cmd = "INSERT INTO comments VALUES(NULL, {0}, {1});".format(senderId, comment)
53+
self.cursor.execute(cmd)
54+
55+
def showComments(self):
56+
cmd = "SELECT * FROM comments"
57+
self.cursor.execute(cmd)
58+
return self.fetchall
59+
60+

0 commit comments

Comments
 (0)
Failed to load comments.