Python study day 40 (ftp exercises to achieve day2)

Today complements some of the features user authentication, and upload files still exist HTTP perfected, where the need to review the knowledge configpraser module, as well as part of the knowledge module os remember still strong, with a few major or can not remember, then that is that.

The main features added today:

  1. The user login authentication, user authentication modified path, directly to each authentication module generates a file configpraser

  2. After the user completes the login by instantiating self.user = user User Rights

  3. Complete the upload function realization part is mainly the case file that already exists and the case file does not exist, the file exists, but under the file is incomplete continue uploading unfinished

  4. File path stitching is very important

  5. Increase the home folder used to store user's profile

  6. Added information table, to reduce the transmission of information during the repeated transmission of content, through the dictionary to find, it is always open before the page jumped out "404" reasons

 

 

 The first is the case of the modified file directory today:

 

 

 The client code updates:

import socket
import optparse
import configparser
import json
import os

STATUS_CODE  = {
    250 : "Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}",
    251 : "Invalid cmd ",
    252 : "Invalid auth data",
    253 : "Wrong username or password",
    254 : "Passed authentication",
    255 : "Filename doesn't provided",
    256 : "File doesn't exist on server",
    257 : "ready to send file",
    258 : "md5 verification",

    800 : "the file exist,but not enough ,is continue? ",
    801 : "the file exist !",
    802 : " ready to receive datas",

    900 : "md5 valdate success"

}
# tcp_client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# tcp_client.connect(('127.0.0.1',8080))
# tcp_client.send('ok'.encode('utf-8'))
# 以上是easy模式下的

class ClientHandler():
    def __init__(self):
        self.op = optparse.OptionParser()

        self.op.add_option('-s','--server', dest = 'server')
        self.op.add_option('-P', '--port',= 'port')
        self.op.add_option('-u', '--username', dest='username')
        self.op.add_option('-p', '--password', dest='password')

        self.options,self.args = self.op.parse_args()

        self.verify_args(self.options,self.args)

        self.make_connection()

        self.mainPath = os.path.dirname(os.path.abspath(__file__))

    def verify_args(self,options , args ):
        # 对port端口进行校验
        server = options.server
        port = options.port
        # username = options.username
        # password = options.password

        if int(port) < 0 and int(port) > 65535:
            return True
        else:
            exit('the port is in 0~65535')

    def make_connection(self):
        self.sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.sock.connect(self.options.server,int(self.options.port))

    def interractive(self):
        if self.authenticate():
            print('==========begin to interactive==========')
            cmd_info = input('[%s]'%self.user).strip()   #比如会输入 put 12.png images

            cmd_list = cmd_info.split('')
            if hasattr(self.cmd_list[0]):
                func = getattr(self,cmd_list[0])
                func(*cmd_list)

    def put(self, *cmd_list):
        # 传入命令: put 12.png images
        action, local_path, target_path = cmd_list
        local_path = os.path.join(self.mainPath , local_path)

        file_name = os.path.basename(local_path)
        file_size = os.stat(local_path).st_size

        data = {
            'action' : 'put',
            'file_name' : file_name,
            'file_size' : file_size,
            'target_path '  : target_path
        } 

        self.sock.sendall (json.dumps (Data) .encode ( ' UTF-. 8 ' )) 
        is_exist = self.sock.recv (1024) .decode ( ' UTF-. 8 ' ) 

        # below received the information is processed (into the service side of writing) 
        has_sent = 0
         IF is_exist == ' 800 ' :
             # indicates that the file exists is incomplete, ie HTTP problems 
            Pass 
        elif is_exist == ' 801 ' :
             # indicates that the file already exists, do not upload, so we put out of way to re-enter the command into the line 
            # that is interractive method 
            Print (" At The File exist " )
             return 
        the else :
             Pass 

        # below indicates the case file does not exist, then begin uploading the 
        f = Open (local_path, " rb " ) 

        the while has_sent < FILE_SIZE: 
            the Data = f.read (1024 ) 
            self.sock .sendall (Data) 
            has_sent + = len (Data) 
            self.show_progress (has_sent, FILE_SIZE) 

        f.close () 

        Print ( " ! PUT Success " ) 

    DEF the authenticate (Self):
         IF self.options.username IS None or self.options.password is None:
            username = input('username>>>')
            password = input('password>>>')
            return get_auth_result(username,password)
        else:
            return get_auth_reult(self.options.username,self.options.password)

    def response(self):
        data = self.sock.recv(1024).decode('utf-8')
        data = json.loads(data)
        return data

    def get_auth_result(self,user ,pwd):
        data = {
            'action' : 'auth',
            'username' : user,
            'password' : pwd
        }

        self.sock.send(json.dumps(data).encode('utf-8'))
        response = self.response()
        print('response是',response['status_code'])

        if response['status_code'] == 254:
            self.user = user
            print(STATUS_CODE[254])
            return True
        else:
            print(STATUS_CODE['status_code'])

ch = ClientHandler()

ch.interractive()

settings file updates:

Import OS 

base_dir = os.path.dirname (os.path.dirname (os.path.abspath with ( __FILE__ ))) 

the IP = ' 127.0.0.1 ' 
PORT = 8080 

ACCOUNT_PATH = the os.path.join (base_dir, ' the conf ' , ' account.cfg ' ) # password information pointing to the client route

Server server.py file updates:

import socketserver
import json
import configparser
from conf import settings
import os

STATUS_CODE  = {
    250 : "Invalid cmd format, e.g: {'action':'get','filename':'test.py','size':344}",
    251 : "Invalid cmd ",
    252 : "Invalid auth data",
    253 : "Wrong username or password",
    254 : "Passed authentication",
    255 : "Filename doesn't provided",
    256 : "File doesn't exist on server",
    257 : "ready to send file",
    258 : "md5 verification",

    800 : "the file exist,but not enough ,is continue? ",
    801 : "the file exist !",
    802 : " ready to receive datas",

    900 : "md5 valdate success"

}

class ServerHandler(socketserver.BaseRequestHandler):

    def handle(self):
        while True:
            data = self.request.recv(1024).strip()
            data = json.loads(data.decode('utf-8'))
            '''
            {'action' : 'auth' ,
             'username' : 'xiao',
             'password' : 123 }
            '''
        if data.get('action'):

            if hasattr(self,data.get('action')):
                func = getattr(self,data.get('action'))
                func(**data)
            else:
                print('func error')
                self.request.send('func error'.encode('utf-8'))
        else:
            print('Invalid cmd')
            self.request.send('Invalid cmd'.encode('utf-8'))

    def send_reponse(self , state_code):
        response = {'status_code':state_code}
        self.request.sendall(json.dumps(response).encode('utf-8'))

    def auth(self,**data):
        username = data['username']
        password = data['password']

        user = self.authenticate(username,password)

        if user:
            self.send_reponse(254)
        else:
            self.send_reponse(253)


    DEF the authenticate (Self, User, pwd): 
        CFG = configparser.ConfigParser () 
        cfg.read (settings.ACCOUNT_PATH) 

        IF User in cfg.sections ():
             IF CFG [User] [ ' password ' ] == pwd: 
                Self. the user = the user   # saved after a successful login a user's login information 
                self.mainPath = os.path.join (settings.BASE_DIR, ' Home ' , self.user)
                 # Print ( 'passed authentication') # represents a successful login 

                return the user 

    DEF PUT (Self, ** Data):
         Print( ' Data ' , Data) 
        file_name = data.get ( ' file_name ' ) 
        FILE_SIZE = data.get ( ' FILE_SIZE ' ) 
        target_path = data.get ( ' target_path ' ) 

        abs_path with = the os.path.join (self.mainPath, target_path , file_name)
         # more portions already obtained in a desired location to save the file server, the file may be opened for subsequent 

        has_received = 0
         iF os.path.exists (abs_path with):
         # for judging whether the file already exists 
            file_has_size =the os.stat (abs_path with) .st_size
             IF file_has_size < FILE_SIZE:
                 # appeared in the case of HTTP 
                self.request.sendall ( ' 800 ' .encode ( ' UTF-. 8 ' ))
                 Pass 
                # continue to improve part 
            the else :
                 # represents a file exists, and more complete, the information returned to the client 801 
                self.request.sendall ( ' 801 ' .encode ( ' UTF-. 8 ' ))
                 return 
        the else : 
            self.request.sendall ( ' 802 '.encode('utf-8'))
            f = open(abs_path , 'wb')
            while has_received < file_size:
                data = self.request.recv(1024)
                f.write(data)
                has_received += len(data)
        f.close()

We will continue tomorrow night HTTP functionality, cd, dir, and other related operations functions

I remember watching configpraser module.

Guess you like

Origin www.cnblogs.com/xiaoyaotx/p/12624056.html