如何在Django中按URL模式重定向?

2024-09-28 20:43:20 发布

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

我有一个Django网站。我想将模式为servertest的URL重定向到相同的URL,除了servertest应该被server-test替换。

因此,例如,以下URL将被映射为重定向,如下所示:

http://acme.com/servertest/                        =>  http://acme.com/server-test/ 

http://acme.com/servertest/www.example.com         =>  http://acme.com/server-test/www.example.com

http://acme.com/servertest/www.example.com:8833    =>  http://acme.com/server-test/www.example.com:8833 

我可以使用url.py中的以下行获得第一个工作示例:

    ('^servertest/$', 'redirect_to', {'url': '/server-test/'}),

不知道如何为其他人做,所以只替换URL的servetest部分。


Tags: djangopytestcomhttpurlserver网站
3条回答

试试这个表达式:

   ('^servertest/', 'redirect_to', {'url': '/server-test/'}),

或者这个:
('^server test','重定向到',{'url':'/server test/'})

It's covered in the docs.

The given URL may contain dictionary-style string formatting, which will be interpolated against the parameters captured in the URL. Because keyword interpolation is always done (even if no arguments are passed in), any "%" characters in the URL must be written as "%%" so that Python will convert them to a single percent sign on output.

(我非常强调。)

然后他们的例子:

This example issues a permanent redirect (HTTP status code 301) from /foo/<id>/ to /bar/<id>/:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    ('^foo/(?P<id>\d+)/$', redirect_to, {'url': '/bar/%(id)s/'}),
)

所以你看这只是一个简单明了的形式:

('^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),

使用以下(为Django 2.2更新):

re_path(r'^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),

它在servertest/之后接受零个或多个字符,并将它们放在/server-test/之后。

或者,您可以使用新的path函数,该函数不使用regex就可以覆盖简单的案例url模式(在Django的新版本中,它是首选):

path('servertest/<path:path>', 'redirect_to', {'url': '/server-test/%(path)s'}),

相关问题 更多 >