How to generate a nginx secure link in python

前端 未结 3 1352
迷失自我
迷失自我 2021-01-17 06:41

How do i make the link for the secure link module in nginx using python? I\'m looking to use nginx to serve secured files that have expiring links. Link to Nginx Wiki

3条回答
  •  半阙折子戏
    2021-01-17 07:15

    The code from shadfc's answer works. For Python 3, some modifications are necessary:

    import base64
    import hashlib
    import calendar
    import datetime
    
    secret = "itsaSSEEECRET"
    url = "/secure/email-from-your-mom.txt"
    
    future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
    expiry = calendar.timegm(future.timetuple())
    
    secure_link = f"{secret}{url}{expiry}".encode('utf-8')
    
    hash = hashlib.md5(secure_link).digest()
    base64_hash = base64.urlsafe_b64encode(hash)
    str_hash = base64_hash.decode('utf-8').rstrip('=')
    
    print(f"{url}?st={str_hash}&e={expiry}")
    

提交回复
热议问题