I have been facing trouble where I could not put the data sent through the server to the database. I used the python's socketserver and sqlite3 class as the server and the database.
Here's my code:
import socketserver
import sqlite3
conn = sqlite3.connect('messages.db', check_same_thread=False)
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS messagesTable(msg BLOB)')
class MyTCPHandler(socketserver.StreamRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.client_address[0]) #the client's ip
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
def put_database(self):
c.execute("INSERT INTO messagesTable(msg) VALUES(?)", self.data)
conn.commit()
if __name__ == "__main__":
HOST, PORT = "localhost", 8888
# Create the server, binding to localhost on port 8888
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
database = MyTCPHandler.put_database()
server.serve_forever()
It's sending messages well, from the client side, and managed to send back the correct data which convinces me that the server is working properly at least. However, it seems that the data is not written into the database messages.db I am new to python and help is much needed. Is there anything wrong with my script or any adjustments that I have to make? Thank you.