开发者

In CherryPy, is it possible to alias a folder name?

I'm using CherryPy. I have a folder named "zh-cn" -- which means that I'm using Mainland China's version of written Chinese - Simplified Chinese.

Here is my code. Notice how I used an underscore? This works.

class ChineseFlashcards:
    zh_cn = ChineseFlashcards_zh_cn()
    en = ChineseFlashcards_en()

My problem is that I'd rather use a hyphen because I think it's "more correct". However, you may not use a hyphen like that in Python. It's not allowed. This throws an error:

class ChineseFlashcards:
    zh-cn = ChineseFlashcards_zh_cn()
    en = ChineseFlashcards_en()

What I'm looking for is some kind of CherryPy attribute that will alias the identifier. Something like this (but this is not legal)

class ChineseFlashcards:
    @cherrypy.expose(alias=['zh-cn'])
    zh_cn = ChineseFlashcards_zh_cn()
    en = ChineseF开发者_开发知识库lashcards_en()

Anyone have a solution to this?


Solution 1: If you're using CherryPy 3.2 or better, just call it 'zh_cn'. See http://docs.cherrypy.org/dev/concepts/dispatching.html#special-characters

Solution 2: you can use setattr to bind attribute names which are not legal Python identifiers:

class ChineseFlashcards:
    en = ChineseFlashcards_en()

setattr(ChineseFlashcards, 'zh-cn', ChineseFlashcards_zh_cn())


The simplest solution is probably to handle that in your own index method. something like this:

class ChineseFlashcards:
    zh_cn = ChineseFlashcards_zh_cn()
    en = ChineseFlashcards_en()

    aliases = {'zh-cn': zh_cn}

    @cherrypy.expose
    def index(self, locale, *args, **kwargs):
        if arg in self.aliases:
            return aliases[locale](*args, **kwargs)

en will still work as normal, so will zh_cn, and any url not recognized will go through index, and it will look in it's own dict of aliases.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜