如何在Django中生成临时URL [英] How to generate temporary URLs in Django

查看:159
本文介绍了如何在Django中生成临时URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有很好的方法可以生成在X天内到期的临时URL。希望通过电子邮件发送一个URL,收件人可以单击该URL以访问站点的一部分,然后在一段时间后无法通过该URL访问该站点的一部分。不知道如何使用Django,Python或其他方式执行此操作。

Wondering if there is a good way to generate temporary URLs that expire in X days. Would like to email out a URL that the recipient can click to access a part of the site that then is inaccessible via that URL after some time period. No idea how to do this, with Django, or Python, or otherwise.

推荐答案

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

If you don't expect to get a large response rate, then you should try to store all of the data in the URL itself. This way, you don't need to store anything in the database, and will have data storage proportional to the responses rather than the emails sent.

已更新:假设您每个用户都有两个唯一的字符串。您可以使用保护性哈希将它们打包并解压缩,如下所示:

Updated: Let's say you had two strings that were unique for each user. You can pack them and unpack them with a protecting hash like this:

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)

这会产生:

849e77ae1b3c eJzTyCkw5ApW90jNyclX5yow4koMVnfPz09JqkwFco25EvUAqXwJnA==
['Hello', 'Goodbye']

在您的电子邮件中,包含一个同时具有哈希值和enc值的URL(正确引用了URL)。在您的视图函数中,将这两个值与decode_data一起使用以检索原始数据。

In your email, include a URL that has both the hash and enc values (properly url-quoted). In your view function, use those two values with decode_data to retrieve the original data.

zlib.compress可能没有帮助,具体取决于您的数据,您可以进行实验看看哪种方法最适合您。

The zlib.compress may not be that helpful, depending on your data, you can experiment to see what works best for you.

这篇关于如何在Django中生成临时URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆