web.py 框架开发网站,当路由过多,怎么分文件编写?

2016-01-20 22:06:09 +08:00
 tomoya92

照着官方给的教程,体验了一下 web.py 框架的简单强大,但当网站的路由稍微多点的话,在一个文件里编写 urls 的实现,就不太好了,我首先想到的是 import 其他的文件进来,这样在主文件里将 urls 配置好,在其他分模块的文件里编写实现就好,但我想将 urls 也一块带到分模块文件里,该怎么操作?

例如:一个论坛,有帖子,回复,用户等模块,每个模块都对应一个 xx.py 文件,在每个文件里定义 urls ,然后实现。

3409 次点击
所在节点    Python
6 条回复
laotaitai
2016-01-20 22:13:51 +08:00
很简单嘛, 在主文件里对各个分模块文件里的 urls 进行合并即可. 框架不是限制你思维的, 是减少你任务量的.
est
2016-01-20 22:19:53 +08:00
blueprint
lichun
2016-01-21 11:14:16 +08:00
换 Django
gemini
2016-01-21 16:25:14 +08:00
这个问题之前也困扰过,挺有趣。我们用 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>
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()
```
hayao650
2016-01-26 16:13:48 +08:00
原谅我,我只是想试一下 markdown

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/252223

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX