import re import pymysql URL_DICT = dict() ''' 给路由添加正则的原因:在实际开发时,URL中往往会带有很多参数,例如:/add/0000007.html,其中 000007(指股票代码:可以用于数据库提取对应的记录)就是参数, 如果此时没有正则的话,那么就要编写N次@route,添加对应的函数到字典中,此时字典中的键值对有N个,浪费空间, 如果采用正则的话,那么只需要编写一次@route就可以完成多个URL,例如/add/00007.html,add/000036.html对应同一个函数,此时字典中的键值对 会少很多 ''' def route(url): def set_func(func): URL_DICT[url] = func def call_func(): func() return call_func return set_func @route(r'/center.html') def center_p(set): pass @route(r'/add/(d+).html') def add_focus(ret): # 获取股票代码 stock_code = ret.group(1) # 判断是否有这个股票代码 conn = pymysql.connect('localhost', 'root', '', 'python_test') cursor = conn.cursor() sql = "select * from info where code=%s" cursor.execute(sql, (stock_code,)) if not cursor.fetchone(): cursor.close() conn.close() return '没有这支股票跑,我们是创业公司,请手下流行' else: # 判断这个股票代码是否已经关注过 sql = 'select *from focus where info_id=%s' cursor.execute(sql, (stock_code,)) if cursor.fetchone(): cursor.close() conn.close() return '已经关注过了,请勿重复关注' else: # 添加关注 sql = 'insert into focus (info_id) select id from info where code=%s' cursor.execute(sql, (stock_code,)) conn.commit() cursor.close() conn.close() return 'add(%s) ok ....' % stock_code @route(r'/add/(d+).html') def del_focus(ret): # 获取股票代码 stock_code = ret.group(1) # 判断是否有这个股票代码 conn = pymysql.connect('localhost', 'root', '', 'python_test') cursor = conn.cursor() sql = "select * from info as i inner join focus as f on i.id=f.info_id where i.code=%s" cursor.execute(sql, (stock_code,)) if not cursor.fetchone(): cursor.close() conn.close() return '没有这支股票跑,我们是创业公司,请手下流行' else: # 判断这个股票代码是否已经关注过 sql = 'select *from focus where info_id=%s' cursor.execute(sql, (stock_code,)) if not cursor.fetchone(): cursor.close() conn.close() return '之前未关注,无法取消' # 添加关注 sql = 'delete into focus (info_id) select id from info where code=%s' cursor.execute(sql, (stock_code,)) conn.commit() cursor.close() conn.close() return 'add(%s) ok ....' % stock_code @route(r'index.html') def index_p(ret): pass def application(env, start_response): '''env是一个空字典,start_response是web服务器里一个方法的引用,函数return的是body''' start_response('200 OK', [('Content-Type', 'text/html;charset=utf-8')]) file_name = env['PATH INFO'] try: # return URL_DICT[file_name]() for url, func in URL_DICT.items(): ''' {r"/index.html":index, r"/center.html":center, r"/add/d+.html":add_focus } ''' ret = re.match(url, file_name) if ret: return func(ret) except Exception as ret: return '产生了异常%s' % str(ret)