2020.4.3项目1

发布于 2020-04-04  25 次阅读


[TOC]
 
# 1.复习内容
 
子网掩码:192.168.0.1/24 意思是24个1,十进制表现形式就是255.255.255.0
 
# 2.灵感代办
 
# 3.学习内容
 
项目开发流程:network-project-day02
词典项目的开发:用到了socket,mysql,多进程
 
```python
"""
 
 
dict_server客户端
"""
 
 
from multiprocessing import Process
import socket
import getpass
import signal
import sys
 
 
from dict_mysql import *
 
 
HOST = '127.0.0.1'
PORT = 8888
ADDR = (HOST, PORT)
 
 
sockfd = socket.socket()
sockfd.connect(ADDR)
 
 
 
 
def input_user():
    name = input("请输入姓名:")
    password = input("请输入密码")
    return name, password
 
 
 
 
def do_login():
    """
    发送数据
    """
    name, password = input_user()
    sockfd.send("login".encode())
    data = name + "#" + password
    sockfd.send(data.encode())
    status = sockfd.recv(1024).decode()
    print_dev(status)
 
 
 
 
def do_register():
    """
    帐号密码
    """
    sockfd.send("register".encode())
    for i in range(2):
        name, password = input_user()
        if name == '' or password == '' \
                                     ' ' in name or ' ' in password:
            print("请重新输入密码")
        else:
            data = name + "#" + password
            sockfd.send(data.encode())
            break
    status = sockfd.recv(1024).decode()
    print_dev(status)
 
 
 
 
def do_return():
    print("do_return")
    sockfd.send('return'.encode())
 
 
 
 
def do_find_word():
    while True:
        sockfd.send("find".encode())
        word = input("请输入要查询的单词")
 
 
        sockfd.send(word.encode())
        print_dev(sockfd.recv(1024).decode())
 
 
 
 
def menu():
    while True:
        try:
            login = sockfd.recv(1024).decode()  # 先知道状态是登录还是注册
            print(login)
            if login == 'false':
                print("--------------------------------")
                print("1)登录")
                print("2)注册")
                print("3)退出")
                print("--------------------------------")
                select_num = int(input("请输入选项:"))
                if select_num == 1:
                    do_login()
                elif select_num == 2:
                    do_register()
                elif select_num == 3:
                    sockfd.send('exit programmer'.encode())
                    return
            elif login == 'true':
                print("--------------------------------")
                print("1)查询")
                print("2)返回上一层")
                print("3)退出")
                print("--------------------------------")
                select_num = int(input("请输入选项:"))
                if select_num == 1:
                    do_find_word()
                elif select_num == 2:
                    do_return()
                elif select_num == 3:
                    sockfd.send('exit login'.encode())
                    sys.exit(1)
        except KeyboardInterrupt as e:
            sockfd.send('exit'.encode())
            sys.exit(1)
 
 
 
 
 
 
def main():
    menu()
 
 
 
 
if __name__ == "__main__":
    main()
```
 
 
```python
"""
 
 
dict_server处理请求逻辑
"""
 
 
from multiprocessing import Process
from socket import *
import signal
import sys
 
 
from dict_mysql import *
 
 
HOST = '127.0.0.1'
PORT = 8888
ADDR = (HOST, PORT)
dict_mysql = DictMysqlHelp()
 
 
 
 
def is_login():
    return dict_mysql.get_login_status().encode()
 
 
 
 
def find_word(connfd):
    try:
        data = connfd.recv(1024).decode()
        print_dev(data)
        explain = dict_mysql.find_word(data)
        print_dev(explain)
        if explain:
            connfd.send(explain[2].encode())
        else:
            connfd.send("查询单词不存在".encode())
    except Exception as e:
        print_dev(e)
 
 
 
 
def do_requset(connfd):
    """
    查询单词
    :return:
    """
    connfd.send(is_login())
    while True:
        try:
            data = connfd.recv(1024).decode()
            if not data:
                break
 
 
            if data == 'return':
                dict_mysql.set_login("false")
                connfd.send(dict_mysql.get_login_status().encode())
 
 
            if data == 'login':
                data = connfd.recv(1024).decode()
                name, password = data.split('#')
                login(connfd, name, password)
 
 
            if data == 'register':
                data = connfd.recv(1024).decode()
                name, password = data.split('#')
                register(connfd, name, password)
 
 
            if data == 'exit' or data == 'exit login' or data == 'exit programmer':
                print(connfd.getpeername(), "退出登录")
                sys.exit(1)
 
 
            if data == "find":
                find_word(connfd)
            print_dev(data)
        except Exception as e:
            print_dev(e)
            break
 
 
 
 
def login(connfd, name, password):
    if dict_mysql.user_login(name, password):
        dict_mysql.set_login("true")
        connfd.send("登录成功".encode())
        connfd.send(dict_mysql.get_login_status().encode())
    else:
        dict_mysql.set_login("false")
        connfd.send("登录失败".encode())
        connfd.send(dict_mysql.get_login_status().encode())
 
 
 
 
def register(connfd, name, password):
    if dict_mysql.user_register(name, password):
        connfd.send("注册成功".encode())
    else:
        connfd.send("注册失败".encode())
 
 
 
 
def main():
    sockfd = socket()
    sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    sockfd.bind(ADDR)
    sockfd.listen(10)
    while True:
        # signal.signal(signal.SIGCHLD, signal.SIG_IGN)
        print("等待客户端连接 ...")
        try:
            connfd, addr = sockfd.accept()
 
 
            print("客户端以连接 ...", addr, connfd)
            process = Process(target=do_requset, args=(connfd,))
            process.start()
        except KeyboardInterrupt:
            sys.exit(1)
        except Exception as e:
            print(e)
            break
 
 
 
 
if __name__ == "__main__":
    main()
```
 
 
 
 
```python
"""
dict词典数据库操作方法集合
"""
import re
from functools import wraps
 
 
import pymysql
 
 
dicts = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "dict",
    "charset": "utf8"
}
dev = True
 
 
 
 
def print_dev(*args, **kwargs):
    if dev is True:
        print(*args, **kwargs)
 
 
 
 
# 装饰器
def try_func(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except Exception as e:
            self.db.rollback()
            print(e)
 
 
    return wrapper
 
 
 
 
class DictMysqlHelp:
    def __init__(self):
        self.db = pymysql.connect(**dicts)
        self.cursor = self.db.cursor()
        # self.init_dict_table()
        # self.init_dict_data("dict.txt")
 
 
    @try_func
    def init_dict_table(self):
        """
        创建三个表
        dict_word 是单词和解释
        dict_user 是注册用户
        dict_history 是查询记录
        :return:
        """
        self.cursor.execute('create database dict')
        self.cursor.execute(
            'create table dict_word(id int primary key auto_increment,`word` varchar(20) not null ,`explain` text not null );')
        self.cursor.execute(
            'create table dict_history(id int primary key auto_increment,`name` varchar(20) unique not null ,`word` varchar(20) not null ,`time` datetime not null );')
        self.cursor.execute(
            'create table dict_user(id int primary key auto_increment,`name` varchar(20) not null ,`password` varchar(20) not null );')
 
 
    @try_func
    def init_dict_data(self, filename):
        """
        初始化词典数据
        :return:
        """
        sql = 'insert into `dict_word`(`word`,`explain`) values(%s,%s)'
        with open(filename, "r") as fd:
            while True:
                data = fd.readline()
                if not data:
                    break
 
 
                split_word = re.split(r'\s{3,}', data)
                word = split_word[0]
                explain = " ".join(split_word[1:])
                # print(explain)
                self.cursor.execute(sql, [word, explain])
        self.db.commit()
 
 
    @try_func
    def save_word(self):
        pass
 
 
    @try_func
    def find_word(self, word=None):
        self.cursor.execute("select * from dict_word where word=%s", (word,))
        return self.cursor.fetchone()
 
 
    @try_func
    def user_login(self, name=None, password=None):
        self.cursor.execute("select * from dict_user where name=%s and password=%s", (name, password))
        return self.cursor.fetchone()
 
 
    @try_func
    def user_register(self, name, password):
        self.cursor.execute("select * from dict_user where name=%s", (name,))
        if not self.cursor.fetchone():
            self.cursor.execute("insert into dict_user(name,password)values(%s,%s)", (name, password))
            return True
        return False
 
 
    @try_func
    def get_login_status(self):
        self.cursor.execute("select login_status from login_status")
        return self.cursor.fetchone()[0]
 
 
    @try_func
    def close_mysql(self):
        self.cursor.close()
        self.db.close()
 
 
    @try_func
    def verity_user(self):
        pass
 
 
    @try_func
    def set_login(self, is_login):
        self.cursor.execute("update login_status set login_status = %s where id = 1", (is_login,))
 
 
 
 
if __name__ == '__main__':
    dicts = DictMysqlHelp()
    dicts.get_login_status()
​``` # 4.扩展延伸知识
easy_install pip
hash加密 ,加盐
```
 
# 5.知识内容个人梳理
 
# 6.今天都复习了之前的什么内容

Ares个人进阶之路