diff --git a/Lesson_6/Task 1/.gitignore b/Lesson_6/Task 1/.gitignore new file mode 100644 index 0000000..8e6ac36 --- /dev/null +++ b/Lesson_6/Task 1/.gitignore @@ -0,0 +1 @@ +messages.db diff --git a/Lesson_6/Task 1/databaseWorker.py b/Lesson_6/Task 1/databaseWorker.py new file mode 100644 index 0000000..4e1daf6 --- /dev/null +++ b/Lesson_6/Task 1/databaseWorker.py @@ -0,0 +1,49 @@ +import sqlite3 +from sqlite3 import Error + +def init_conn(path): + conn = None + try: + conn = sqlite3.connect(path) + print ("Connection established!") + except Error as e: + print (e) + print ("Connection failed!") + return conn + +def init_tables(connection): + sql = "CREATE TABLE IF NOT EXISTS messages( id integer PRIMARY KEY, nickname text NOT NULL, message text NOT NULL);" + connection.execute(sql) + +def prepareDb(name): + conn = init_conn(name) + init_tables(conn) + conn.close() + +def getMessages(name): + connection = init_conn(name) + sql = "SELECT * FROM messages;" + cursor = connection.cursor() + cursor.execute(sql) + rows = cursor.fetchall() + connection.close() + + return rows + +def generateMessagesHTMLTable(rows): + messagesTable = "" + for row in rows: + messagesTable += "" + for cell in row: + messagesTable += "" + messagesTable += "" + messagesTable += "
" + str(cell) + "
" + return messagesTable + +def sendMessage(db, nickname, message): + connection = init_conn(db) + sql = "INSERT INTO messages(`nickname`, `message`) VALUES('{}', '{}')".format(nickname, message) + cursor = connection.cursor() + cursor.execute(sql) + connection.commit() + connection.close() diff --git a/Lesson_6/Task 1/templates/index.html b/Lesson_6/Task 1/templates/index.html new file mode 100644 index 0000000..4a038e1 --- /dev/null +++ b/Lesson_6/Task 1/templates/index.html @@ -0,0 +1,34 @@ + + + + Chat + + +
+
+
+
+
+ +
+ Messages: +
+
+ {{messages|safe}} +
+ + + diff --git a/Lesson_6/Task 1/webserver.py b/Lesson_6/Task 1/webserver.py new file mode 100644 index 0000000..2295f0e --- /dev/null +++ b/Lesson_6/Task 1/webserver.py @@ -0,0 +1,24 @@ +from databaseWorker import * +from flask import Flask, render_template, redirect, request + +app = Flask("Chat") +prepareDb("messages.db") + +@app.route('/') +def index(): + rows = getMessages("messages.db") + return render_template("index.html", messages=generateMessagesHTMLTable(rows)) + +@app.route('/send') +def send(): + nickname = request.args.get('nickname') + message = request.args.get('message') + sendMessage("messages.db", nickname, message) + return redirect('/') + +@app.route('/getMessagesTable') +def getMessagesTable(): + rows = getMessages("messages.db") + return generateMessagesHTMLTable(rows) + +app.run(host='0.0.0.0', port=8081)