Add Lesson 6 Task 1

This commit is contained in:
Stanislav Mykhailenko 2023-01-06 23:35:22 +02:00
parent e2e4599c25
commit ef62307e08
GPG key ID: 1E95E66A9C9D6A36
4 changed files with 108 additions and 0 deletions

1
Lesson_6/Task 1/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
messages.db

View file

@ -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 = "<table border='1'>"
for row in rows:
messagesTable += "<tr>"
for cell in row:
messagesTable += "<td>" + str(cell) + "</td>"
messagesTable += "</tr>"
messagesTable += "</table>"
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()

View file

@ -0,0 +1,34 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chat</title>
</head>
<body>
<form action="/send">
<label for="nickname">Nickname: </label><br>
<input type="text" id="nickname" name="nickname"><br>
<label for="message">Message: </label><br>
<textarea id="message" name="message" rows="5" cols="50"></textarea><br>
<button id="submit" type="submit">Submit</button>
</form>
Messages:
<hr>
<div id="messages">
{{messages|safe}}
</div>
<script>
function getMessages() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("messages").innerHTML = this.responseText;
}
xhttp.open("GET", "/getMessagesTable", true);
xhttp.send();
}
window.setInterval(() => {
getMessages();
}, 1000);
</script>
</body>
</html>

View file

@ -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)