简体   繁体   中英

Twilio - generate 6 digit random numbers

Im planning to integrate twilio for two factor authentication in my Django application.

Now, I have installed twilio python module and sent some random messages to my number.

The next step is for me to send some random 6 digit numbers that's done in banking application or google two factor authentication.

How can I generate these numbers in my DJango application?

In addition to Matthias' answer (I upvoted his answer); Django provides a shortcut function for this purpose:

from django.utils.crypto import get_random_string

get_random_string(length=6, allowed_chars='1234567890')

Which is more readable and memorable.

And also if you are really concerned about randomness of this string, you may want to use random module from pycrypto because standard library implementations of random function in programming languages are not "random" enough for cryptographic and security related issues.

You can use random.choice to determine each digit. choice will give you one element from the given sequence.

The code could look like this:

import random
pin = ''.join(random.choice('0123456789') for _ in range(6))

you could also do

import random
random.SystemRandom().randint(100000,999999)

Twilio developer evangelist here.

There have been some great answers to help you generate a random 6 digit string, however I just wanted to add one more suggestion.

Authy is part of Twilio and provides Two Factor Authentication as a service. It supports sending codes by SMS (which goes via Twilio), generating codes in the Authy application and even two factor authentication without copying a code from an app/sms to your login screen with Authy OneTouch . You can implement your entire 2FA flow with just 3 API calls.

There is a tutorial on how to use Authy with Flask , which I'm sure you could translate to Django.

Let me know if this helps at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM