python实现的NoSql数据库系列-数据库初始化功能

本文主要是涵盖了基础结构部分的代码,包括
1. constant.py
2. message.py
3. order.py
4. db_main.py
5. config.py
6. db_opr_decorator.py
# constant.py
# -*-coding:utf-8-*-
EXIT = 'exit'
# message.py
# -*-coding:utf-8-*-
ALLOW = ' >>>'
SPACE = '   '
EXEL = ' ! '
MSG_INPUT = 'Please input your command' + ALLOW
ORDER_NOT_EXIST = SPACE + 'Order is not exist' + EXEL + 'Please input again'
ADD_PARAMS_NOT_EXIST = SPACE + 'Additional parameters is not exist' + EXEL + 'Please input again'
NOT_OPERANDS = SPACE + 'Only order' + EXEL + 'Please input operands'
UNKNOWN_ERROR = SPACE + 'Unknown error' + EXEL + 'Please chech syntax again'
EXE_ERROR = SPACE + 'Execute order error' + EXEL + 'Please check syntax again'
EXE_SUCCESS = SPACE + 'ok!'

# 类型错误
NOT_STR_OR_INT = SPACE + 'Value type error' + EXEL + 'Not [str or int] , please user other order'
NOT_LIST = SPACE + 'Value type error' + EXEL + 'Not [list] , please user other order'
NOT_DICT = SPACE + 'Value type error' + EXEL + 'Not [dict] , please user other order'
NOT_ALLOW = SPACE + 'Not allowed order or operands' + EXEL + 'Please user other order or chech syntax again'
DICT_PARAMS_ERROR = SPACE + 'Dict error' + EXEL + 'Please check params again'
LIST_PARAMS_ERROR = SPACE + 'List error , index must be number not str' + EXEL + 'Please check params again'
NOT_DATA = SPACE + 'Str or int or list or dict is not exist' + EXEL + 'Please create or change'
EMPTY_SEQ = SPACE + 'Empty sequence cannot be sorted'
UNSUPPORTED_SORTED = SPACE + 'Unsupported sorted sequences'
UNSUPPORTED_OPR = SPACE + 'Unsupported operation'
UNSUPPORTED_ORDER = SPACE + 'Unsupported order'

# 作者信息

AUTHOR_INFO = '[Author info] Author : MADAO , QQ : 1506795308'
ONE_STAR = '*'

# 人性化信息
WELCOME_INFO = '*' * 50 + '\n' \
               + ONE_STAR + '{welcome}'.format(welcome='Welcome to use PY_NoSql!').center(48) + ONE_STAR + '\n' \
               + ONE_STAR + '{version}'.format(version='version 1.0').center(48) + ONE_STAR + '\n' \
               + ONE_STAR + '{info:^20}'.format(info=AUTHOR_INFO).center(48) + ONE_STAR + '\n' \
               + '*' * 50 + '\n'

MSG_THANK = 'Thank your for use!'
HELP_INFO = {'set': 'set',
             'get': 'get',
             'del': 'del',
             'setl': 'set_list',
             'getl': 'get_list',
             'dell': 'del_list',
             'setol': 'set_olist',
             'getol': 'get_olist',
             'delol': 'del_olist',
             'setd': 'set_dict',
             'getd': 'get_dict',
             'deld': 'del_dict',
             'len': 'len',
             'count': 'count',
             'max': 'max',
             'min': 'min',
             'sort': 'sortl',
             'copy': 'copyl',
             'in': 'contain',
             'format': 'formatnum',
             'round': 'roundnum',
             'change': 'change',
             'merge': 'merge',
             'join': 'join'}
# order.py
# -*-coding:utf-8-*-
"""
    这里主要是指令集字符串
    基本指令字符串,[param]代表可选参数,默认为None,空列表或空字典
    指令格式:指令 操作数 --附加参数    注意,操作数可以多个
    1 新增set key [val]
    2 查找get key
    3 修改set key [val]
    4 删除del key

    5 创建或者新增命名列表 setl listname [val] 没有值的时候创建空列表
    6 按索引/成员查找列表 getl listname [val] -idx/mem 没有参数是删除整个列表
    7 按索引/成员删除   dell listname val -idx/mem  -idx是按索引删除,-mem是按成员删除

    8 创建有序列表 setol listname [index] [val] 没有值的时候创建空列表
    9 按索引/成员查找列表 getol listname [val] -idx/mem 没有参数是删除整个列表,
    10 按索引/成员删除   delol listname val -idx/mem  -idx是按索引删除,-mem是按成员删除

    11 创建新增字典 setd dictname [key] [val] 没有值得时候默认创建空字典,有键值的时候添加
    12 按键查找列表 getd dictname [key]
    13 按键删除 deld dictname [key]

    高级指令字符串
    0 通用操作,帮助文档
    1 通用操作,长度计算 len key
    2 通用操作,进行某个值得统计 count key val
    3 通用操作,最大值   max key
    4 通用操作,最小值   min key
    5 通用操作,排序(升序和降序) sort key
    6 通用操作,复制            copy source_key target_key
    7 通用操作,成员判断         contain val key
    8 数值,支持精度操作         format key
    9 数值,支持四舍五入操作     round key
    10 字符串,支持大小写转换    change key --up/low
    11 字符串,修改拼接         merge key new_val
    12 支持简单的连接操作       join list/dict list/dict
"""
BASIC = 'basic_'
ADVANCE = 'adv_'
BASIC_ORDER_DEFINE = {
    'set': BASIC + 'set',
    'get': BASIC + 'get',
    'del': BASIC + 'del',
    'setl': BASIC + 'set_list',
    'getl': BASIC + 'get_list',
    'dell': BASIC + 'del_list',
    'setol': BASIC + 'set_olist',
    'getol': BASIC + 'get_olist',
    'delol': BASIC + 'del_olist',
    'setd': BASIC + 'set_dict',
    'getd': BASIC + 'get_dict',
    'deld': BASIC + 'del_dict'
}

ADVANCE_ORDER_DEFINE = {
    'len': ADVANCE + 'len_val',
    'count': ADVANCE + 'count_val',
    'max': ADVANCE + 'max_val',
    'min': ADVANCE + 'min_val',
    'sort': ADVANCE + 'sort_val',
    'copy': ADVANCE + 'copy_val',
    'contain': ADVANCE + 'contain',
    'format': ADVANCE + 'format_num',
    'round': ADVANCE + 'round_num',
    'change': ADVANCE + 'change',
    'merge': ADVANCE + 'merge',
    'join': ADVANCE + 'join'}

ADD_PARAMS_DEFINE = {
    'up': 'upper',
    'low': 'lower'
}

ALLOW_ORDER = {
    1: ['set', 'get', 'del', 'setl', 'getl',
        'setol', 'getol', 'setd', 'getd', 'len', 'max', 'min', 'sort', 'change'],
    2: ['set', 'setl', 'getl', 'dell', 'setol',
        'getol', 'delol', 'setd', 'getd', 'deld',
        'count', 'copy', 'in', 'format', 'round', 'merge'],
    3: ['setl', 'setol', 'setd']
}
# db_main.py
# -*-coding:utf-8-*-
from python_based_db.constant import EXIT
from python_based_db.db_advanced_opr import AdvancedOperation
from python_based_db.db_basic_opr import BasicOperation
from python_based_db.message import *
from python_based_db.order import *

basic = BasicOperation()
advance = AdvancedOperation()


# 处理主流程
def exe_process(order_name):
    if not order_name:
        return

    # 解析指令
    try:
        order, operands, add_param, exe_fun = parse_order(order_name)
    except:
        return

    # 执行指令,基本指令和高级指令

    try:

        if order in BASIC_ORDER_DEFINE:
            execute = getattr(basic, exe_fun)
            basic.params = operands
        else:
            execute = getattr(advance, exe_fun)
            advance.params = operands

        result = execute()
        if result:
            print(SPACE + str(result))
    except AttributeError:
        print(UNSUPPORTED_ORDER)
    except Exception as e:
        print(EXE_ERROR)
    else:
        print(EXE_SUCCESS)


# 解析指令,解析正确,会返回(指令,操作数,附加参数,执行函数)
def parse_order(order_name):
    # 检查是否存在指令
    try:
        order_list = order_name.split(' ')
        order_len = len(order_list)

        basic_fun = BASIC_ORDER_DEFINE.get(order_list[0])
        adv_fun = ADVANCE_ORDER_DEFINE.get(order_list[0])
        exe_fun = basic_fun if basic_fun else adv_fun

        add_param = None

        # 判断指令是否定义
        if not exe_fun:
            print(ORDER_NOT_EXIST)
            return

        # 判断是否只有指令
        if order_len == 1:
            print(NOT_OPERANDS)
            return

        # 判断是否有附加参数,有附加参数必须指令列表order_list长度超过2
        if order_len > 2 and '--' in order_list[order_len - 1]:
            add_param = order_list[order_len - 1][2:]
            # 判断附加参数是否定义
            if not ADD_PARAMS_DEFINE.get(add_param):
                print(ADD_PARAMS_NOT_EXIST)
                return

        # 进行指令和操作数的判断
        order = order_list[0].lower()

        # 没有附加参数的情况下
        if not add_param:
            operands = tuple(order_list[1:order_len])
        else:
            operands = tuple(order_list[1:order_len - 1])

        # 判断是否合法操作
        if not is_allow_opr(order, operands):
            return

        return order, operands, add_param, exe_fun
    except:
        print(UNKNOWN_ERROR)


def is_allow_opr(order, operands):
    # 判断是否合法的数据类型操作,比如字符串和数值只允许用set,get,del指令,列表要用setl等指令
    # 这里按操作数的数量和特殊字符来进行判断
    operands_len = len(operands)

    # 所有超过3个操作数的都算3个
    operands_len = 3 if operands_len >= 3 else operands_len

    # 判断指令是否允许操作
    if order not in ALLOW_ORDER.get(operands_len):
        print(NOT_ALLOW)
        return False

    # 如果是字典指令setd,要单独判断,按照约束,只需要判断操作数里的:数量是否等于1
    if order == 'setd' and operands_len > 1:
        operands_data = operands[1:]
        for data in operands_data:
            if data.count(':') != 1:
                print(DICT_PARAMS_ERROR)
                return False

    return True


if __name__ == '__main__':
    print(WELCOME_INFO)
    while True:
        order_input = input(MSG_INPUT)
        if order_input.strip().lower() == EXIT:
            print(MSG_THANK, AUTHOR_INFO, sep='\n')
            break
        exe_process(order_input)

# db_opr_decorator.py
from python_based_db.message import NOT_DATA

# 判断数据存在,并设值装饰器
def is_exist_data(exe_fun):
    def wapper(self, *args, **kwargs):
        try:
            self.data = self.db[self.params[0]]
            return exe_fun(self)
        except:
            print(NOT_DATA)
    return wapper
# config.py

你可能感兴趣的:(python实现的NoSql数据库系列-数据库初始化功能)