python - 如何在python服务器中连接sql3
问题描述
我在 python 中编写了简单的服务器,但它无法写入和读取 sqldatabase。
服务器连接到 android java 程序,数据通过正常,但服务器不写入或读取 sql。
import json
import socket
import threading
import sqlite3
import time
IP = "0.0.0.0"
PORT = 6040
# the connection to the sql database
#####db_connection = sqlite3.connect('asia.db')
# sqlite3.connect connect to database
#####cursor = db_connection.cursor()
# The command cursor creates a pipe (called cursor) to the database through which you can run queries,
# perform actions and get their answers.
# cursor.execute('''CREATE TABLE users(user text UNIQUE, password text, fname text, lname text)''')
def add(user: str, password: str, fname: str, lname: str):
# adds the current user to the database if his user name isnt already exist - user (UNIQUE)
try:
con = sqlite3.connect('asia.db')
cur = con.cursor()
cur.execute("INSERT INTO users VALUES (?, ?, ?, ?)",
(user, password, fname, lname))
con.commit() # Save (commit) the changes
print("changes saved")
return True
except sqlite3.IntegrityError as unique_exception:
print(f"{unique_exception}, User already registered")
return False
def login(user: str, password: str):
# finds if user in this username exist in the database and if the passwords between the emails matches
con = sqlite3.connect('asia.db')
cur = con.cursor()
db_user = cur.execute(f"SELECT user From users Where user = '{user}'") # check if user exist
if db_user.fetchone() is None:
return False
else:
db_password = cur.execute(f"SELECT Password From users Where user = '{user}'") # index
if db_password:
db_password = db_password.fetchone()[0] # getting out of the index
if db_password == password:
return True
else:
return False
else: # password incorrect
return False
def request_handler(json_request, client_socket):
# handles request by the value of the request key of the object
print(json_request)
if json_request["request"] == "add":
if add(
json_request["user"],
json_request["password"],
json_request["fname"],
json_request["lname"]
):
print(json_request["user"], "is registered")
json_response = {"response": "welcome"}
client_socket.send(json.dumps(json_response).encode())
else:
print(json_request["user"], "is already exist")
json_response = {"response": "email already exist"}
client_socket.send(json.dumps(json_response).encode())
elif json_request["request"] == "login":
if login(json_request["user"], json_request["password"]):
print("login succeed")
json_response = {"response": "Hey there"}
client_socket.send(json.dumps(json_response).encode())
else:
print("login didn't succeed")
json_response = {"response": "Login didn't succeed"}
client_socket.send(json.dumps(json_response).encode())
else:
print("invalid data")
json_response = {"response": "Check again"}
client_socket.send(json.dumps(json_response).encode())
client_socket.close()
def handle_connection(client_socket: socket.socket, ip_address: str):
# the connection to the client
print("new connection from:", ip_address)
request = client_socket.recv(1024).decode()
json_request = json.loads(request) # Loads the data(string) to the json object
request_handler(json_request, client_socket) # starts handling the clients request
client_socket.close()
def main():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((IP, PORT))
print("Starting server...")
print("port = ", PORT)
print("ip = ", IP)
server_socket.listen()
while True:
new_client = server_socket.accept()
new_thread = threading.Thread(target=handle_connection,
args=new_client) # Creating a thread to handle the connection
new_thread.start() # starts the handling process
if __name__ == '__main__':
main()
解决方案
推荐阅读
- google-cloud-platform - GCP - 启用外部身份提供程序
- java - 除非我在应用信息设置中手动授予它的权限,否则通知声音不起作用
- docusignapi - DocuSign API JAVA - 如何以编程方式填写每个签名者的字段公司和标题
- c# - DisplayAttribute:无法检索属性“名称”,因为本地化失败
- php - 我想要内容旋转的所有结果 - 已解决
- webpack - 压缩发生在 __WB_MANIFEST 注入之前
- android - 如何使用 fl_chart 显示工具提示指示器?
- java - 如何检查字符串是否仅包含运算符?
- python - 不可能在 Python 中请求 WCF,而 C# 可以
- matplotlib - 无法实现 matplotlib.pyplot.canvas.draw() 进行实时绘图