Search code examples
pythonlocalizationcherrypycjk

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 = ChineseFlashcards_en()

Anyone have a solution to this?


Solution

  • 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())