正在加载...

tornado-6 url

tornado的url就是下面的形式:

urls = [
    (r'/user/show/',UserShow),
    (r'/user/login/', UserLogin),

    (r'/group/maillist/', GroupMaillist),
]

每组元素的第一个是url,第2个是对应的Controller

没有太多好说的。这里给出一个封装,用来自动的进行route

首先要求,项目目录如下:

目录

接下来,就是url的自动生成了。我写了一个route.py的文件

具体看代码吧

route.py

#coding: utf-8
import os
import sys

def __url_of(module_name):
    return '/'.join([ v for v in module_name.split('_') if v ])

def reasoning():
    from app.controllers.base_controller import BaseController
    valible_suffix = ['/']
    controllers_dir = 'app/controllers'
    controllers_package = '.'.join(controllers_dir.split('/'))
    controllers_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', controllers_dir))
    urls = []
    for _, _, files in os.walk(controllers_dir):
        for f in files:
            if f == 'base_controller.py' or not f.endswith('controller.py'):
                continue

            prefix_name = f[0:-3] # 3 为 len('.py')
            model_name = prefix_name[0:-11]  # 11 为 len('_controller')
            module_name = controllers_package + '.' + prefix_name
            module = __import__(module_name, fromlist=['*']) # 导入所有的内容到内存中

            for class_name in dir(module):
                try:
                    obj = getattr(module, class_name)
                    if obj is BaseController or not issubclass(obj, BaseController):
                        continue
                except TypeError, _:
                    continue

                clazz = getattr(module, class_name)
                controller_file_name = module_name.split('.')[-1]
                for suffix in valible_suffix:
                    if controller_file_name != 'index_controller':
                        url = '/%s/%s%s' % (__url_of(model_name), class_name.lower(), suffix)
                    else: # 如果是index_controller,那么映射只有class name,controller name 不要  
                        url = '/%s%s' % (class_name.lower(), suffix)    
                    urls.append((url, clazz))

                if class_name.lower() == 'index':
                    for suffix in valible_suffix:
                        if controller_file_name != 'index_controller':
                            url = '/%s%s' % (__url_of(model_name), suffix)
                            urls.append((url, clazz))
    return urls


def special():
    import app.controllers as controllers
    mapping = {
        '/': controllers.user_controller.Login
    }
    urls = []
    for url, clazz in mapping.iteritems():
        urls.append((url, clazz)) 
    return urls


def all():
    def merge(all_urls_dict, mappings):
        for mapping in mappings:
            url, clazz = mapping[0], mapping[1]
            all_urls_dict[url] = (url, clazz)

    def merge_of(reasoning, special):
        all = {}
        merge(all, reasoning)
        merge(all, special)
        urls = all.values()
        urls.sort()
        return urls

    return merge_of(reasoning(), special())


def show(url_mappings):
    for mapping in url_mappings:
        print mapping


if __name__ == '__main__':
    name = 'all'
    if len(sys.argv) == 2 and sys.argv[1] in ('all', 'reasoning', 'special'):
        name = sys.argv[1]
    urls = eval(name)()
    show(urls)

对于controller的写法如下:

company_controller.py

#coding: utf-8

from app.controllers.base_controller import BaseController

class Index(BaseController):

    def get(self):
        pass

    def post(self):
        pass


class List(BaseController):

    def get(self):
        pass

    def post(self):
        pass


class Create(BaseController):

    def get(self):
        pass

    def post(self):
        pass

class Show(BaseController):

    def get(self):
        pass

    def post(self):
        pass


class Update(BaseController):

    def get(self):
        pass

    def post(self):
        pass