我一直遇到麻烦,我无法将通过服务器发送的数据放到数据库中。我使用python的socketserver和sqlite3类作为服务器和数据库。
这是我的代码:
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
server.serve_forever()
它从客户端很好地发送消息,并设法发回正确的数据,这让我确信服务器至少正常工作。但是,似乎数据没有写入数据库messages.db 我是python的新手,非常需要帮助。我的脚本或我必须做出的任何调整是否有任何问题?谢谢。
更新: 所以,我尝试在if语句中调用put_database,它给了我错误。代码是这样的:
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()** << i put it here..
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
它错过了一个&#34; self&#34;论点。我怎么称这个方法?在哪里?