一個裝飾器的例子

需求是:用文件的方式模擬select,insert 等操做 由於是模擬,不用數據庫模塊實現 用文件模擬數據庫,記錄形式是 id,name,dept,phoe,eroll_data記錄到磁盤 支持select ,insert 等標準形式的sql語法 用了兩個 模塊實現需求 sql_func.py 用來執行sql操做 mock_sql.py用來解析用戶的輸入 其中,在mock_sql.py裏面用了裝飾器parse_user_input用來解析用戶的輸入,經過這個裝飾器,獲得用戶不一樣的sql語句對應的表名,字段名,和限定條件(好比where 子句後面的條件),和insert 操做裏的values的內容 用了反射的方法去匹配不一樣的insert/delete/update/select的具體函數 具體到sql_func.py裏面實現的都是字符串解析,經過字符串解析獲取內容,寫入文件 sql_func裏面的 read_file()函數實現讀取文件,對應select功能 sql_func裏面的get_last_line實現讀取當前文件的最後一行的功能,這個是爲了給insert用的 ,inser實現id自增,須要判斷當前最後一行的id號 sql_func裏面的write_file()函數實現寫文件 文件名: sql_func.pypython

# coding:utf-8

import re
import os

def insert(action_name, dbname, fieldname, condition_limit, condition_values):
    print "action:", action_name, dbname, fieldname, condition_limit
    # insert into staff (name, dept, phone, eroll_date) values (li, DEV, 123456677, 20110101)
    write_file(dbname, fieldname, condition_limit, condition_values)

def delete(action_name, dbname, fieldname, condition_limit, condition_values):
    print "action:", action_name, dbname, fieldname, condition_limit

def update(action_name, dbname, fieldname, condition_limit, condition_values):
    print "action:", action_name, dbname, fieldname, condition_limit

def select(action_name, dbname, fieldname, condition_limit, condition_values):
    print "action:", action_name, dbname, fieldname, condition_limit
    read_file(dbname, fieldname, condition_limit)

def read_file(fname, fieldname, condition_limit):
    with open(fname, "r") as fd:
            for line in fd:
                if fieldname == "*" and condition_limit == "no":
                    print line.strip("\n")
                elif fieldname == "*" and condition_limit != "no":
                    condition_item = condition_limit.strip(";").split()[0].strip('"')
                    condition_signal = condition_limit.strip(";").split()[1]
                    condition_value = condition_limit.strip(";").split()[2].strip('"')
                    if condition_item == "name" and condition_signal == "=":
                        if line.strip("\n").split(",")[1] == condition_value:
                            print line.strip("\n")
                    elif condition_item == "dept":
                        if line.strip("\n").split(",")[2] == condition_value:
                            print line.strip("\n")
                    elif condition_item == "eroll_date" and condition_signal == "like":
                        if line.strip("\n").split(",")[4].__contains__(condition_value):
                            print line.strip("\n")


def get_last_line(fname):
    block_size = 1024
    with open(fname, "r") as fd:
        file_size = os.path.getsize(fname) 
        if file_size > block_size:
            seek_point = (file_size // block_size)
            fd.seek((seek_point - 1) * file_size)
        else:
            fd.seek(0, 0)
        lines = fd.readlines()
        if lines:
            last_line = lines[-1].strip()
        print last_line    
    return last_line

def write_file(fname, fieldname, condition_limit, condition_values):
    with open(fname ,"a+") as fd:
        last_line = get_last_line(fname) 
        cur_max_id = last_line.split(",")[0]
        print cur_max_id
        item = ",".join(condition_values.split(","))
        record = re.sub(r'"| ', "", item.strip()).strip("(").strip(")")
        record_id = int(cur_max_id) + 1
        fd.writelines(str(record_id) + "," + record)

文件名: mock_sql.py正則表達式

# coding:utf-8

'''
sql_func是導入的另一個模塊,即位於同級目錄的sql_func.py

需求語法:
    insert into tablename
    delete from tablename
    delete from tablename where clause
    update tablename set filedname=value
    update tablename set (fieldname1, fieldname2, fieldname3...) values (val1, val2, val3...)
    select * from tablename where clasuse
    select filedname from tablename where clause
'''

import re
import sql_func

def parse_user_rawinput(func):
    # 拆分字符串得到表名的正則表達式
    re_parse_dbname = r"' '+|from|update|into"
    # 拆分字符串得到字段名的正則表達式
    re_field_name = r"select|from|set|where|into|values|="
    # 拆分字符串得到where條件的正則表達式
    re_condition = r"where"
    # 拆分是insert into插入記錄的狀況下的values的正則表達式
    re_insert_values = r"values"
    def wrapper_parse(user_input):
        user_action_pointer, user_line, user_sql = func(user_input)
        if user_action_pointer in ["select", "delete","insert", "update"]:
            user_action_pointer, user_sql, user_line = func(user_input)
            dbname = re.split(re_parse_dbname, user_line)[1].lstrip().split()[0].rstrip(";")
            fieldname = re.sub(r"(^.* )\(", "", re.split(re_field_name, user_line)[1]).strip(" )")
            if user_action_pointer in ["select", "delete", "update"]:
                condition = re.split(re_condition, user_line)
                if len(condition) == 1:
                    condition_limit = "no"
                else:
                    condition_limit = condition[1]
            elif user_action_pointer == "insert":
                condition_limit = "no"
                condition_values = re.split(re_insert_values, user_line)[1]
            sql_action(user_action_pointer, dbname, fieldname, condition_limit, condition_values)
        else:
           print  "invalid action"
           return "invalid action"
           exit(1)
    return wrapper_parse

@parse_user_rawinput
def parse_user_input(user_input):
    user_action_pointer = user_input["user_sql_list"][0]
    user_sql = user_input["user_sql_list"]
    user_line = user_input["user_line"]
    return user_action_pointer, user_sql, user_line

def sql_action(action_name, dbname, fieldname, condition_limit, condition_values):
    if action_name in ["select", "insert", "update", "delete"]:
        if hasattr(sql_func, action_name):
            func = getattr(sql_func, action_name)
            result = func(action_name, dbname, fieldname, condition_limit, condition_values)

def input():
    user_results = dict()
    user_line = raw_input("input your sql:")
    user_sql_list = user_line.rstrip(";").split()
    user_results["user_line"] = user_line
    user_results["user_sql_list"] = user_sql_list
    return user_results

if __name__ == "__main__":
    user_input = input()
    parse_user_input(user_input)

1,zhang,DEV,13600010001,20100101 2,wang,DEV,1360020002,20110101 3,zhao,OPS,13600030005,20110201 4,qian,OPS,13600040006,20130203 5,sun,OPS,13600050007,20070709 6,li,OPS,13600060008,20150602 7,wu,OPS,13600070009,20160703sql

相關文章
相關標籤/搜索