我有一个类似于stackoverflow的网址 像:
http://sample.com/post/12345/hello-world
但是我想让以下网址在cherrypy中运行:
http://sample.com/post/12345/hello-world?from=something&else=123
应该更正:
http://sample.com/post/12345/hello-world
我该怎么做?
我使用popargs和_cp_dispatch但没有成功。任何建议将不胜感激。
感谢
修改
我根据saaj的回答让它工作,但我想将代码移动到index(),并且url都返回404.
import cherrypy
class App:
@cherrypy.expose
def index(self, id, name = None, **kwargs):
if kwargs:
# do your querystring processing
raise cherrypy.HTTPRedirect(cherrypy.url())
if not name:
# get name part for canonical url
name = '{0}/hello-world'.format(id)
raise cherrypy.HTTPRedirect(cherrypy.url(name))
return '{0} {1} {2}'.format(id, name, kwargs)
if __name__ == '__main__':
cherrypy.quickstart(App(), '/post', config)
再也非常感谢帮助了。我仍然是一个快乐的初学者。
答案 0 :(得分:1)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cherrypy
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8
},
}
class App:
@cherrypy.expose
def index(self):
return '''
<ul>
<li>
<a href='/post/12345/hello-world'>/post/12345/hello-world</a>
</li>
<li>
<a href='/post/12345/hello-world?from=something&else=123'>
/post/12345/hello-world?from=something&else=123</a>
</li>
<li><a href='/post/12345'>/post/12345 (more like SO)</a></li>
</ul>
'''
@cherrypy.expose
def post(self, id, name = None, **kwargs):
if kwargs:
# do your querystring processing
raise cherrypy.HTTPRedirect(cherrypy.url())
if not name:
# get name part for canonical url
name = '{0}/hello-world'.format(id)
raise cherrypy.HTTPRedirect(cherrypy.url(name))
return '{0} {1} {2}'.format(id, name, kwargs)
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)