Ton*_*nyM 5 python django django-urls
我有一个基于Django的网站。我想将其中包含模式的URL重定向servertest到相同的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
Run Code Online (Sandbox Code Playgroud)
我可以使用urls.py中的以下行来获取第一个示例:
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
Run Code Online (Sandbox Code Playgroud)
不确定如何为其他用户执行此操作,因此仅替换了URL的servetest部分。
使用以下内容(针对Django 2.2更新):
re_path(r'^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),
Run Code Online (Sandbox Code Playgroud)
后面要包含零个或多个字符,servertest/然后再放置它们/server-test/。
另外,您可以使用新path功能来覆盖简单情况下的网址格式,而无需使用正则表达式(并且在新版本的Django中首选):
path('servertest/<path:path>', 'redirect_to', {'url': '/server-test/%(path)s'}),
Run Code Online (Sandbox Code Playgroud)
给定的URL可能包含字典样式的字符串格式,该格式将根据URL中捕获的参数进行插值。由于关键字插值总是做(即使没有参数被传入),网址中的所有“%”字符必须写成“%%”,这样Python将其转换为一个百分号输出。
(重点突出。)
然后是他们的例子:
此示例发出从/ foo / <id> /到/ bar / <id> /的永久重定向(HTTP状态代码301):
Run Code Online (Sandbox Code Playgroud)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'}),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6163 次 |
| 最近记录: |