We’re almost there! Now we need to save the tokens we’ve generated as well as the phone number requesting it. While can be done anywhere I chose to plop it into the generate_token() method because we’d have to write the code twice otherwise. Luckily its a small fix, and we’ll finally be able to use our database stuff now.
Just before the “return token” line in the method add these lines:
try: up = phone.select().where(phone.digits==number).get() except: up = phone.create(digits=number) records = SelectQuery(tokens).where(tokens.phone==up.id).count() if records: tokens.update(token=token).where(tokens.phone==up.id).execute() else: tokens.create(token=token,phone=up.id)
The first try/except block attempts to get the phone information from the database and creates a record of it instead if nothing exists. We then try to update the token for the phone number and if that doesn’t work then we create a new record of it. Very simple and easy but is also vital to our service.