在cherrypy中默认根视图

2024-03-29 15:59:33 发布

您现在位置:Python中文网/ 问答频道 /正文

some source code我是 写作时,我可以提出如下请求:

http://proxy.metaperl.org/index/bitgold-rw1

并成功地重定向。在

但是,我想从URL中删除index,并保留它 使用index()方法重定向。我尝试将index()重命名为 default()在阅读 Dispatching, 但它仍然不允许我有这样的网址:

^{pr2}$

它试图找到一个名为bitgold-rw1的方法,而不是使用 解决请求的默认方法,将错误告知我:

NotFound: (404, "The path '/bitgold-rw1' was not found.")

WSGI启动文件如下所示:

# -*- python -*-

# core
import os
import sys

# 3rd party
import cherrypy

# local
def full_path(*extra):
    return os.path.join(os.path.dirname(__file__), *extra)

sys.path.insert(0, full_path())
import config
import myapp

application = cherrypy.Application(
    myapp.Root(),
    "/",
    config.config)

Tags: path方法importconfigindexossyssome
3条回答

仅重命名为default是不够的。它至少需要有可变参数*args可调用才能接收路径段。像这样:

#!/usr/bin/env python3


import cherrypy


config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}


class Root:

  @cherrypy.expose
  def default(self, *args, **kwargs):
    cherrypy.log('{0}, {1}'.format(args, kwargs))
    return 'OK'


if __name__ == '__main__':
  cherrypy.quickstart(Root(), '/', config)

然后它将捕获http://127.0.0.1:8080/bitgold-rw1/和{}之类的东西。在

顺便说一句,如果它是关于MVC的,它是一个控制器,而不是一个视图。在

如果在根类中将索引方法重命名为“default”,这应该可以。在

添加线条

在cherrypy快速入门(根())

在底部我的app.py用python运行它我的app.py'您的服务器应该启动并监听端口8080。 向http://localhost:8080/bitgold-rw1发出请求对我有效,它抱怨我不是美国公民,我想这没问题;-)

如@ralhei@saaj所述,如果您不想在cherrypy中处理调度程序,那么缺省方法就是关键。我尝试了下面的代码并按你的意愿工作

class Root(object):

    @cherrypy.expose
    def index(self, tag):
        redirect_url = db.urls[tag]
        ip = cherrypy.request.headers['Remote-Addr']
        request_url = 'http://ipinfo.io/{0}/country'.format(ip)
        r = requests.get(request_url)
        country = r.text.strip()
        raise cherrypy.HTTPRedirect(redirect_url)

    @cherrypy.expose
    def default(self,tag):
        return self.index(tag)

相关问题 更多 >