Skip to content

Instantly share code, notes, and snippets.

@michaeljs1990
Created August 19, 2014 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaeljs1990/27b3e9b1fd5e50338082 to your computer and use it in GitHub Desktop.
Save michaeljs1990/27b3e9b1fd5e50338082 to your computer and use it in GitHub Desktop.
sqlite3 oddness
# output from print as seen in my console.
[18/Aug/2014:21:41:00] HTTP Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/cherrypy/_cprequest.py", line 670, in respond
response.body = self.handler()
File "/usr/local/lib/python3.4/dist-packages/cherrypy/lib/encoding.py", line 217, in __call__
self.body = self.oldhandler(*args, **kwargs)
File "/usr/local/lib/python3.4/dist-packages/cherrypy/_cpdispatch.py", line 61, in __call__
return self.callable(*self.args, **self.kwargs)
File "/home/mschuett/python/CherryBlog/CherryBlog/admin.py", line 49, in settings
title = admin.AdminModel.getKey("site_title")
File "/home/mschuett/python/CherryBlog/CherryBlog/models/admin.py", line 62, in getKey
print(cursor.fetchone()[1])
TypeError: 'NoneType' object is not subscriptable
import sqlite3
import hashlib
import binascii
class AdminModel(object):
@classmethod
def connector(cls):
return sqlite3.connect('CherryBlog/models/app.db')
# Check for the existence of a user in the database
# return @bool
@staticmethod
def userExists():
db = AdminModel.connector()
cursor = db.execute('''SELECT COUNT(*) FROM users;''')
if cursor.fetchone()[0] == 0:
return False;
else:
return True
# Add new user to the database
@staticmethod
def addUser(username, password):
db = AdminModel.connector()
uname = username.encode('utf-8')
# Secure Hashing for the password
passwd = AdminModel.computeHash(password)
cursor = db.execute("INSERT INTO users(username, password) VALUES (?, ?);", (uname, passwd))
try:
db.commit()
return True
except Exception as err:
return False
# Return an array of username and hashed password
@staticmethod
def getUser(username):
db = AdminModel.connector()
cursor = db.execute("SELECT * FROM users WHERE username=?;", (username.encode('utf-8'),))
return cursor
@staticmethod
def computeHash(password, salt="magicpy"):
dk = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt.encode('utf-8'), 100000)
return binascii.hexlify(dk)
# Return the value of a given key as listed
# inside of the database.
# Returns False on failed key lookup
@staticmethod
def getKey(key):
db = AdminModel.connector()
cursor = db.execute("SELECT * FROM options WHERE key=?;", (key.encode('utf-8'),))
print(cursor.fetchone()[1])
import cherrypy
from voluptuous import Schema, Required, All, Length, Range, MultipleInvalid, Invalid
from jinja2 import Environment, FileSystemLoader
# Import needed models
from CherryBlog.models import admin
# Houses all top level pages
class AdminPages(object):
def __init__(self, env):
self._env = env
# Render Page
def render(self, page, **kwargs):
menu = {"Settings":"/admin/settings", "Pages":"/admin/pages", "Blog":"/admin/blog"}
keys = {"template":page, "menu":menu, "header": "Admin"}
for key in kwargs:
keys[key] = kwargs[key]
tmpl = self._env.get_template('partials/body.html')
return tmpl.render(keys)
@cherrypy.expose
def index(self):
return self.render("admin.html")
# Only called by the cherrypy framework when logging
# in for the first time.
@staticmethod
def login(realm, username, password):
row = admin.AdminModel.getUser(username)
try:
verify = row.fetchone()[1]
if verify == admin.AdminModel.computeHash(password):
return True
except Exception as err:
return False
# Allow user to set random blog settings and turn flags on
# and off such as site title and pages.
@cherrypy.expose
def settings(self):
# Get the site title
title = admin.AdminModel.getKey("site_title")
return self.render("settings.html", title=title)
@cherrypy.expose
def pages(self):
pass
@cherrypy.expose
def blog(self):
pass
# Output as seen in console
CherryBlog
import sqlite3
import hashlib
import binascii
class AdminModel(object):
@classmethod
def connector(cls):
return sqlite3.connect('CherryBlog/models/app.db')
# Check for the existence of a user in the database
# return @bool
@staticmethod
def userExists():
db = AdminModel.connector()
cursor = db.execute('''SELECT COUNT(*) FROM users;''')
if cursor.fetchone()[0] == 0:
return False;
else:
return True
# Add new user to the database
@staticmethod
def addUser(username, password):
db = AdminModel.connector()
uname = username.encode('utf-8')
# Secure Hashing for the password
passwd = AdminModel.computeHash(password)
cursor = db.execute("INSERT INTO users(username, password) VALUES (?, ?);", (uname, passwd))
try:
db.commit()
return True
except Exception as err:
return False
# Return an array of username and hashed password
@staticmethod
def getUser(username):
db = AdminModel.connector()
cursor = db.execute("SELECT * FROM users WHERE username=?;", (username.encode('utf-8'),))
return cursor
@staticmethod
def computeHash(password, salt="magicpy"):
dk = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt.encode('utf-8'), 100000)
return binascii.hexlify(dk)
# Return the value of a given key as listed
# inside of the database.
# Returns False on failed key lookup
@staticmethod
def getKey(key):
db = AdminModel.connector()
cursor = db.execute("SELECT * FROM options WHERE key='site_title';")
print(cursor.fetchone()[1])
@michaeljs1990
Copy link
Author

output from:

PRAGMA TABLE_INFO(options);
cid name type notnull dflt_value pk
0 key varchar(250) 1 1
1 value TEXT 0 0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment