What is the standard method for generating a nonce in Python?

前端 未结 5 1513
清歌不尽
清歌不尽 2021-02-12 12:48

Can someone share the best practices for creating a nonce for an OAuth request in Python?

5条回答
  •  醉酒成梦
    2021-02-12 13:22

    Here are a few ideas I got for emailage. The generate_nonce comes from their code, but I use generate_nonce_timestamp which I used uuid for. It gives me a random alpha-numeric string and a time stamp in seconds:

    import random
    import time
    import uuid
    
    
    def generate_nonce(length=8):
        """Generate pseudo-random number."""
        return ''.join([str(random.randint(0, 9)) for i in range(length)])
    
    
    def generate_timestamp():
        """Get seconds since epoch (UTC)."""
        return str(int(time.time()))
    
    def generate_nonce_timestamp():
        """Generate pseudo-random number and seconds since epoch (UTC)."""
        nonce = uuid.uuid1()
        oauth_timestamp, oauth_nonce = str(nonce.time), nonce.hex
        return oauth_nonce, oauth_timestamp
    

    I like using uuid1, since it generates the uuid based on current host and time and has the time property that you can extract if you need both. For emailage, you need both the timestamp and the nonce.

    Here is what you get:

    >>> generate_nonce_timestamp()
    ('a89faa84-6c35-11e5-8a36-080027c336f0', '136634341422770820')
    

    If you want to remove the -, use nonce.get_hex().

    uuid1 - Generate a UUID from a host ID, sequence number, and the current time. More on uuid.

提交回复
热议问题