重写了
This commit is contained in:
parent
fb3e4cdd68
commit
4c13e8bc83
115
CS3.1.py
Normal file
115
CS3.1.py
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
import threading
|
||||||
|
import json
|
||||||
|
from flask import Flask, jsonify, request
|
||||||
|
import sqlite3
|
||||||
|
import socket
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
socket_server = socket.socket()
|
||||||
|
socket_server.bind(("localhost", 8888))
|
||||||
|
def get_db_connection():
|
||||||
|
conn = sqlite3.connect("usr.db")
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
def isuserxist(name):
|
||||||
|
cn = get_db_connection()
|
||||||
|
csr = cn.cursor()
|
||||||
|
csr.execute('SELECT * FROM users WHERE name = ?', (name,))
|
||||||
|
rst = csr.fetchone()
|
||||||
|
cn.close()
|
||||||
|
if rst is not None:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def ispsswdright(name,passwd):
|
||||||
|
cn = get_db_connection()
|
||||||
|
csr = cn.cursor()
|
||||||
|
csr.execute("SELECT COUNT(*) FROM users WHERE name=?", (name,))
|
||||||
|
row_count = csr.fetchone()[0]
|
||||||
|
password = None
|
||||||
|
if row_count > 0:
|
||||||
|
csr.execute("SELECT passwd FROM users WHERE name=?", (name,))
|
||||||
|
password = csr.fetchone()[0]
|
||||||
|
if password == passwd:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
@app.route("/api/register", methods=['POST'])
|
||||||
|
def register(usr = None,pwd = None):
|
||||||
|
conn = get_db_connection()
|
||||||
|
vl = request.get_json()
|
||||||
|
if usr == None and pwd == None:
|
||||||
|
usr = vl.get('username')
|
||||||
|
pwd = vl.get('password')
|
||||||
|
|
||||||
|
csr2 = conn.cursor()
|
||||||
|
csr2.execute('SELECT * FROM users WHERE name = ?', (usr,))
|
||||||
|
result = csr2.fetchone()
|
||||||
|
if result is not None:
|
||||||
|
return jsonify({
|
||||||
|
"success": False,
|
||||||
|
"message": "Username already exists"
|
||||||
|
}), 403
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
conn = get_db_connection()
|
||||||
|
cursor = conn.cursor()
|
||||||
|
|
||||||
|
cursor.execute("INSERT INTO users (name, passwd) VALUES (?, ?)", (usr, pwd))
|
||||||
|
conn.commit()
|
||||||
|
except sqlite3.Error as e:
|
||||||
|
print (e)
|
||||||
|
return jsonify({
|
||||||
|
"success": False,
|
||||||
|
"message": str(e)
|
||||||
|
}), 500
|
||||||
|
else:
|
||||||
|
return jsonify({
|
||||||
|
"success": True,
|
||||||
|
"message": "User registered successfully"
|
||||||
|
})
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
def handle_socket_message(data):
|
||||||
|
try:
|
||||||
|
action = data.get('type')
|
||||||
|
if action == 'register':
|
||||||
|
return register(data.get('username'), data.get('password'))
|
||||||
|
elif action == 'login':
|
||||||
|
if isuserxist(data['username']):
|
||||||
|
if ispsswdright(data['username'], data['password']):
|
||||||
|
return {"status": "success", "message": "Login successful"}
|
||||||
|
return {"status": "error", "message": "Invalid credentials"}
|
||||||
|
except Exception as e:
|
||||||
|
return {"status": "error", "message": str(e)}
|
||||||
|
def run_socket_server():
|
||||||
|
socket_server.listen()
|
||||||
|
print("Socket server running on port 8888")
|
||||||
|
while True:
|
||||||
|
conn, addr = socket_server.accept()
|
||||||
|
print(f"Socket client connected: {addr}")
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
data = conn.recv(1024)
|
||||||
|
if not data: break
|
||||||
|
|
||||||
|
try:
|
||||||
|
json_data = json.loads(data.decode())
|
||||||
|
response = handle_socket_message(json_data)
|
||||||
|
conn.sendall(json.dumps(response).encode())
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
conn.sendall(json.dumps(
|
||||||
|
{"success": "error", "message": "Invalid JSON"}
|
||||||
|
).encode())
|
||||||
|
except ConnectionResetError:
|
||||||
|
print(f"Client {addr} disconnected")
|
||||||
|
finally:
|
||||||
|
conn.close()
|
||||||
|
if __name__ == '__main__':
|
||||||
|
threading.Thread(target=run_socket_server, daemon=True).start()
|
||||||
|
with get_db_connection() as conn:
|
||||||
|
conn.execute('''CREATE TABLE IF NOT EXISTS users
|
||||||
|
(name TEXT, passwd TEXT)''')
|
||||||
|
app.run(port=5001)
|
Loading…
x
Reference in New Issue
Block a user