2013-03-05 54 views
0

我想设置一个简单的通知,如果一个视图有一个特定的基础引用。通过正则表达式匹配referer

假设我登陆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的问题。

+0

顺便说一句 - 因为你指出的回报并不重要......实际上它是在Web应用中非常重要。如果您在计划的控制流程结束时没有返回(例如:认证失败),但只是执行重定向,则可能会使自己暴露于不期望的影响:-) – 2013-04-04 15:38:58

+0

是的,我只是表示返回后会发生什么。 '这里没有关系。即与这个问题无关。 – 2013-04-04 15:45:16

回答

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)