照着官方给的教程,体验了一下 web.py 框架的简单强大,但当网站的路由稍微多点的话,在一个文件里编写 urls 的实现,就不太好了,我首先想到的是 import 其他的文件进来,这样在主文件里将 urls 配置好,在其他分模块的文件里编写实现就好,但我想将 urls 也一块带到分模块文件里,该怎么操作?
例如:一个论坛,有帖子,回复,用户等模块,每个模块都对应一个 xx.py 文件,在每个文件里定义 urls ,然后实现。
1
laotaitai 2016-01-20 22:13:51 +08:00
很简单嘛, 在主文件里对各个分模块文件里的 urls 进行合并即可. 框架不是限制你思维的, 是减少你任务量的.
|
2
est 2016-01-20 22:19:53 +08:00
blueprint
|
3
lichun 2016-01-21 11:14:16 +08:00
换 Django
|
4
gemini 2016-01-21 16:25:14 +08:00 1
这个问题之前也困扰过,挺有趣。我们用 uswgi 启动 python 应用的,启动时”自动“对应的业务模块。
对每个模块约定文件结构,比如直接是 xxx.py 或者子目录且入口类文件名与子目录名称一致(当然也可以约定其他的) <pre><code> ## import apps/目录下所有应用 def auto_add_route(): excludes = ".svn common" routes = [] for f in os.listdir(os.getcwd()): ## the same dir with gops.py if f in excludes: continue importstr = "" fn = f ispkg = True if os.path.isdir(f): importstr = "from %s import %s" %(f, f) else: ispkg = False if f.endswith('.py'): fn, fe = f.split('.') importstr = "import %s" %fn if len(importstr) == 0: continue try: exec importstr except ImportError: print "[ERROR] import failed, [%s]" %importstr pass ## add route r = "/myproject/apps/" + fn classname = fn mod = "" try: mod = __import__(classname, None, None, ['']) except ImportError: print "[ERROR] import failed, [%s]" % classname pass if ispkg: mod = getattr(mod, classname, None) inst = getattr(mod, "app", None) routes.append(r) routes.append(inst) return routes urls = tuple(auto_add_route()) app = web.application(urls, globals()) application = app.wsgifunc() if __name__== "__main__": app.run() </code></pre> |
5
hayao650 2016-01-26 16:12:17 +08:00
```python
## import apps/目录下所有应用 def auto_add_route(): excludes = ".svn common" routes = [] for f in os.listdir(os.getcwd()): ## the same dir with gops.py if f in excludes: continue importstr = "" fn = f ispkg = True if os.path.isdir(f): importstr = "from %s import %s" %(f, f) else: ispkg = False if f.endswith('.py'): fn, fe = f.split('.') importstr = "import %s" %fn if len(importstr) == 0: continue try: exec importstr except ImportError: print "[ERROR] import failed, [%s]" %importstr pass ## add route r = "/myproject/apps/" + fn classname = fn mod = "" try: mod = __import__(classname, None, None, ['']) except ImportError: print "[ERROR] import failed, [%s]" % classname pass if ispkg: mod = getattr(mod, classname, None) inst = getattr(mod, "app", None) routes.append(r) routes.append(inst) return routes urls = tuple(auto_add_route()) app = web.application(urls, globals()) application = app.wsgifunc() if __name__== "__main__": app.run() ``` |
6
hayao650 2016-01-26 16:13:48 +08:00
原谅我,我只是想试一下 markdown
|