Python study day 39 (ftp exercises to achieve day1)

The next three days or four days or five days also, I will begin to implement a process of ftp record, in fact, somewhat similar function Baidu network disk, carried out a preliminary implementation:

The main requirements:

 

The key is to do some of the main logic, carried out to verify the password steps:

File directory as follows:

 

 Mainly introduce server-side document it,

European port bin file

conf configuration file (containing port information, user information)

core logic master file (primary logical operation)

logger operation log file

 

It is still relatively rough stage.

First introduce the service side of the main code:

bin file: ftp_server.py

import os,sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from core import main

if __name__ == '__main__':
    main.ArgvHandler()

core file: main.py

import socketserver
import optparse

from conf import settings
from core import server


class ArgvHandler():

    def __init__(self):
        self.op = optparse.OptionParser ()
         # self.op.add_option ( '- S', '- Server', dest = 'Server') 
        # self.op.add_option ( '- P', '- P' , dest = 'Port') 
        # analysis module, temporarily not used to, it is argv input parameters to come in the form of key-value pairs to save, print out like a dictionary, but it is not a dictionary, by. way to call 
        Options, args = self.op .parse_args ()

        # Is assumed that the initial input parameters for the operation of 127.0.0.1 -p 8080 -s 
        # Print (Options) {# 'Server': '127.0.0.1', 'Port': 8080} 
        # Print (type (Options)) # data type options are optparse instance object 
        # Print (args) # no parameters for subsequent reception of those identifiers that are prefixed

        self.verify_args(options,args)

    def verify_args(self,options ,args):

        cmd = args[0]
        if hasattr(self,cmd):
            func = getattr(self,cmd)
            func()

    def start(self):
        print('==========welcome ftp_server==========')
        s = socketserver.ThreadingTCPServer((settings.IP , settings.PORT),server.ServerHandler)
        s.serve_forever()

core file: server.py

import socketserver
import json

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 auth(self,**data):
        print(data)

    def put(self,**data):
        pass

conf file: settings.py

IP = '127.0.0.1'
PORT = 8080

About server is currently so much, but a lot of features still just a pass, and so much time on weekends and then one by one logical file written down, although he is now finished, but did not keep up his mind still in a state of

 

Here is the client content, currently realized verify the information entered ip address, port information

At the same time interacting authentication username and password information with the server

The client (ftp_client):

Import Socket
 Import The optparse
 Import ConfigParser
 Import JSON
 # tcp_client = socket.socket (socket.AF_INET, socket.SOCK_STREAM) 
# tcp_client.connect (( '127.0.0.1', 8080)) 
# tcp_client.send ( 'ok'.encode (' . 8-UTF ')) 
# above is the easy mode

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

        self.op.add_option('-s','--server', dest = 'server')
        self.op.add_option('-P', '--port', dest='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()

    DEF verify_args (Self, Options, args):
         # of the port port verify 
        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):
        self.authenticate()

    def 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)


ch = ClientHandler()

ch.interractive()

Today, user name verification need to brush up configpraser information module, as the focus of tomorrow's direction right now password authentication client is not a problem, the server can not achieve

Continue tomorrow, I slept.

Almost forgot, today also learn a optparse module for processing information input in argv mode, making it modular, the modules have to see a detailed tomorrow, this really sleep

Guess you like

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