zoukankan      html  css  js  c++  java
  • 第三十四节 路由添加正则功能以及添加关注功能

    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'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)
  • 相关阅读:
    android通过httpClient请求获取JSON数据并且解析
    Http请求之HttpClient + AsyncTask异步请求
    HttpClient使用线程锁synchronized
    经典讨论(四)
    DRP学习进化模型
    ftk学习记录(button一片)
    MySQL检查连接的最大数量和改变的最大连接数
    Android_开发人员经常使用的颜色
    jQuery组织您钞四----jQuery操作DOM
    Codeforces 461B Appleman and Tree(木dp)
  • 原文地址:https://www.cnblogs.com/kogmaw/p/12602582.html
Copyright © 2011-2022 走看看