如何在Django中生成临时URL

cha*_*ool 19 django url

想知道是否有一种很好的方法来生成在X天内过期的临时URL.想要通过电子邮件发送一个URL,收件人可以点击该URL以访问该网站的一部分,该网站在一段时间后通过该URL无法访问.不知道如何使用Django,或Python,或其他方式.

Ned*_*der 16

如果您不希望获得较大的响应率,那么您应该尝试将所有数据存储在URL本身中.这样,您不需要在数据库中存储任何内容,并且数据存储与响应成比例,而不是发送的电子邮件.

更新:假设您有两个对每个用户都唯一的字符串.您可以打包它们并使用这样的保护哈希解压缩它们:

import hashlib, zlib
import cPickle as pickle
import urllib

my_secret = "michnorts"

def encode_data(data):
    """Turn `data` into a hash and an encoded string, suitable for use with `decode_data`."""
    text = zlib.compress(pickle.dumps(data, 0)).encode('base64').replace('\n', '')
    m = hashlib.md5(my_secret + text).hexdigest()[:12]
    return m, text

def decode_data(hash, enc):
    """The inverse of `encode_data`."""
    text = urllib.unquote(enc)
    m = hashlib.md5(my_secret + text).hexdigest()[:12]
    if m != hash:
        raise Exception("Bad hash!")
    data = pickle.loads(zlib.decompress(text.decode('base64')))
    return data

hash, enc = encode_data(['Hello', 'Goodbye'])
print hash, enc
print decode_data(hash, enc)
Run Code Online (Sandbox Code Playgroud)

这会产生:

849e77ae1b3c eJzTyCkw5ApW90jNyclX5yow4koMVnfPz09JqkwFco25EvUAqXwJnA==
['Hello', 'Goodbye']
Run Code Online (Sandbox Code Playgroud)

在您的电子邮件中,包含一个既包含哈希值又包含enc值的URL(正确的url-quoted).在view函数中,将这两个值与decode_data一起使用以检索原始数据.

zlib.compress可能没那么有用,根据您的数据,您可以尝试查看最适合您的方法.


Mat*_*ell 5

您可以使用如下 URL 进行设置:

http://yoursite.com/temp/1a5h21j32
Run Code Online (Sandbox Code Playgroud)

你的 URLconf 看起来像这样:

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^temp/(?P<hash>\w+)/$', 'yoursite.views.tempurl'),
)
Run Code Online (Sandbox Code Playgroud)

...其中 tempurl 是一个视图处理程序,它根据哈希值获取适当的页面。或者,如果页面过期,则发送 404。


zal*_*lew 5

楷模

class TempUrl(models.Model):
    url_hash = models.CharField("Url", blank=False, max_length=32, unique=True)
    expires = models.DateTimeField("Expires")
Run Code Online (Sandbox Code Playgroud)

意见

def generate_url(request):
    # do actions that result creating the object and mailing it

def load_url(request, hash):
    url = get_object_or_404(TempUrl, url_hash=hash, expires__gte=datetime.now())
    data = get_some_data_or_whatever()
    return render_to_response('some_template.html', {'data':data}, 
                              context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)

网址

urlpatterns = patterns('', url(r'^temp/(?P<hash>\w+)/$', 'your.views.load_url', name="url"),)
Run Code Online (Sandbox Code Playgroud)

//当然你需要一些导入和模板