2013-03-05 50 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)