keywords

pymongo split key, value = ['key', 'value'] [x for x] exp if condition esle MethodDict exception

Checkout

  1. 连接数据库
from pymongo import MongoClient
client = MongoClient() # 本地连接
coll = client.staff.emp # 获取数据集
  1. 拆分字符串
command = 'add id=1 name=carson age=17 sex=male salary=22222'
command_list = command.split() # type: array | split with space(' ')
opeartion = command_list[0]

para_dic = generate_operation_dict(command_list[1:]) # arr[1] ~ arr[-1]

def generate_operation_dict(self, para_list):
    operation_dict = {}
    try:
        for para in para_list:
            key, value = para.split('=')
            operation_dic[key] = value
        return operation_dict
    except Excetion as e:
        print 'sorry, para error: {}'.formate(e)
    return
  1. [x for x]
  2. exp if cond else
[x for x in range(1,4)] # [1, 2, 3]

def check_if_id_exists(self, emp_id)
    return True if [x for x in self.coll.find({'id': emp_id})] else False
  1. MethodDict
def init(self):
    self.operationDict = {
        'add': self.add_emp,
        'update': self.update_emp,
        'delete': self.delete,
        'show': self.show_emp,
        'help': self.help,
        'exit': exit
    }

operation = command_list[0]
if operation in self.operationDict:
    para_dict = generate_para_dict(command_list[1:])
    self.operation_dict[operation](para_dict) \
        if operation not in ['help', 'exit'] \
        else self.operation_dict[operation]()
else:
    self.operation_dic['help']
return
  1. 字符串对齐
table = 'id'.ljust(20) + \
        'name'.ljust(20) + \
        'age'.center(20) + \
        'sex'.center(20) + \
        'salary'.rjust(20) + '\n'
for emp in result:
    try:
        table += str(emp['id']).ljust(20) + \
                 emp['name'].ljust(20) + \
                 str(emp['age']).center(20) + \
                 emp['sex'].center(20) + \
                 str(emp['salary']).rjust + '\n'
    except Exception as e:
        print 'sorry, because: {}'.formate(e)
print table
  1. 抓异常
try:
    # 1. para_dict[name] = value
    # 2.

results matching ""

    No results matching ""