Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Tour-Guide/DbUserFactory.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
40 lines (33 sloc)
1.41 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
from werkzeug.security import generate_password_hash, check_password_hash | |
import sqlite3 | |
from UserFactory import UserFactory | |
from user import User | |
class DbUserFactory(UserFactory): | |
def __init__(self, db_path='guideschedule.db'): | |
self.db_path = db_path | |
self.local = threading.local() | |
def get_connection(self): | |
if not hasattr(self.local, 'conn'): | |
self.local.conn = sqlite3.connect(self.db_path) | |
return self.local.conn | |
def create_table(self): | |
conn = self.get_connection() | |
conn.execute(''' | |
CREATE TABLE users ( | |
id INTEGER PRIMARY KEY AUTOINCREMENT, | |
name TEXT UNIQUE NOT NULL, | |
password TEXT NOT NULL | |
) | |
''') | |
conn.commit() | |
def create_user(self, name, password): | |
conn = self.get_connection() | |
hashed_password = generate_password_hash(password, method='pbkdf2:sha256', salt_length=8) | |
dbuser_cur = conn.execute('select * from users where name = ?', [name]) | |
existing_username = dbuser_cur.fetchone() | |
if existing_username: | |
raise ValueError('Username already taken, try different username.') | |
conn.execute('insert into users (name, password) values (?, ?)', [name, hashed_password]) | |
conn.commit() | |
return User(name, hashed_password) | |