[Django]-Twilio โ€“ generate 6 digit random numbers

0๐Ÿ‘

โœ…

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.

๐Ÿ‘คphilnash

12๐Ÿ‘

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.

5๐Ÿ‘

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))
๐Ÿ‘คMatthias

1๐Ÿ‘

you could also do

import random
random.SystemRandom().randint(100000,999999)
๐Ÿ‘คpragman

0๐Ÿ‘

rand(1000, 9999); == 4 digit
rand(100000, 999999); == 6 digit

$client = $this->_initTwilioClient();
    $fromNo = $this->_helperPot->getTwilioPhone();
    $code = rand(1000, 9999);
    try {
        $result = $client->messages->create(
            $toNo,
            [
                'from' => $this->_helperPot->getTwilioPhone(),
                'body' => "Verification code: $code"
            ]
        );
        $output = [];
        $output['status'] = "success";
        $output['code'] = $code;
        return $output;
    } catch (\Exception $e) {
        $output = [];
        $output['status'] = "failure";
        $output['message'] = $e->getMessage();
        return $output;
    }
๐Ÿ‘คManish Goswami

Leave a comment