通过正则表达式匹配来源网址

0 投票
1 回答
511 浏览
提问于 2025-04-17 17:56

我想设置一个简单的通知,条件是某个页面有特定的来源网址。

比如说,我访问了 http://myapp.com/page/,而我之前是从 http://myapp.com/other/page/1 过来的。下面是我写的伪代码,基本上就是如果我来自任何页面/X,我想设置一个通知。

我在想可能会像 ^r^myapp.com/other/page/$ 这样,但我对在Python中使用正则表达式不是很熟悉。

from django.http import HttpRequest
def someview(request): 
     notify = False
     ... # other stuff not important to question
     req = HttpRequest()
     test = req.META['HTTP_REFERER'] like "http://myapp.com/other/page*"
     # where * denotes matching anything past that point and the test returns T/F
     if test:
        notify = True

    return # doesn't matter here

这可能更多的是“我在这个情况下如何使用正则表达式”,而不单单是关于Django的问题。

1 个回答

2

你可以试试这样的写法:

import re
referrer = "http://myapp.com/other/page/aaa"
m = re.match("^http://myapp.com/other/page/(.*)", referrer)
if m:
    print m.group(1)

撰写回答