def init_db(): """Initializes the database.""" sqlite3.register_converter('GUID', lambda b: uuid.UUID(bytes_le=b)) sqlite3.register_adapter(uuid.UUID, lambda u: buffer(u.bytes_le)) for i in range(0, 3): db = get_db(i) with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
def __init__(self, db_path, disable_sqlite_crypt=False): self.db_path = db_path self.con = None self.disable_sqlite_crypt = disable_sqlite_crypt self._log = logging.getLogger('DB') self._lock = threading.Lock() dbapi2.register_adapter(bool, int) dbapi2.register_converter("bool", lambda v: bool(int(v)))
def init_db(): """ register_converter(): convert SQLite types to Python types register_adapter(): convert Python types to SQLite types """ sqlite3.register_converter('GUID', lambda b: uuid.UUID(bytes_le=b)) sqlite3.register_adapter(uuid.UUID, lambda u: buffer(u.bytes_le)) for i in range(0, 3): #with app.app_context(): db = get_db(i) #db = queries._engine.raw_connection() with app.open_resource('tracks.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit()
def init_db(): """Initializes the database.""" schema = open('schema.sql', 'r') schema_commands = schema.read() schema.close(); sqlite3.register_converter('GUID', lambda b: uuid.UUID(bytes_le=b)) sqlite3.register_adapter(uuid.UUID, lambda u: buffer(u.bytes_le)) for database in DATABASES: try: db = get_db(database) db.cursor().executescript(schema_commands) db.commit() except sqlite3.Error, err: print " [INFO] %s " % err
def _connectdb(self, filename): # Register the adapter sqlite.register_adapter(Compressed, adapt_compressed) sqlite.register_converter("compressed", convert_compressed) if os.path.exists(filename): need_create = False else: need_create = True conn = sqlite.connect(filename, detect_types=sqlite.PARSE_DECLTYPES, check_same_thread = False) if need_create: self._createdb(conn) else: if not self._validatedb(conn): # TODO: should clobber existing tables? self._createdb(conn) return conn
def main(): # Allow this script which uses multiprocessing to be frozen to produce a # Windows executable. if setlyze.FROZEN: multiprocessing.freeze_support() # Initilize the logger. if setlyze.FROZEN: level = logging.ERROR elif sys.flags.debug: # Print debug messages if the PYTHONDEBUG env variable is set. Also # print debug messages for the multiprocessing module. level = logging.DEBUG multiprocessing.log_to_stderr(logging.DEBUG) else: level = logging.INFO logging.basicConfig(level=level, format='%(levelname)s %(message)s') # Registers adapt_str to convert the custom Python type into one of SQLite's # supported types. This adds support for Unicode strings. sqlite.register_adapter(str, adapt_str) # Set some signal handlers. setlyze.sender.connect('on-start-analysis', on_start_analysis) # Create an info message. logging.info("SETLyze %s started." % setlyze.__version__) # Display the main window. select_analysis.show() # Start the GTK main loop. gtk.main() # Terminate the application once the main GTK loop is terminated. sys.exit()
def __init__(self, databaseDir): self.dataBasePath = os.path.join(databaseDir, 'MyGames.db') sqlite.register_adapter(str, lambda s: s.decode('utf-8')) #use scripts home for reading SQL files self.sqlDir = os.path.join(util.RCBHOME, 'resources', 'database')
try: import decimal except ImportError: from django.utils import _decimal as decimal # for Python 2.3 DatabaseError = Database.DatabaseError IntegrityError = Database.IntegrityError Database.register_converter("bool", lambda s: str(s) == '1') Database.register_converter("time", util.typecast_time) Database.register_converter("date", util.typecast_date) Database.register_converter("datetime", util.typecast_timestamp) Database.register_converter("timestamp", util.typecast_timestamp) Database.register_converter("TIMESTAMP", util.typecast_timestamp) Database.register_converter("decimal", util.typecast_decimal) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) class DatabaseFeatures(BaseDatabaseFeatures): supports_constraints = False class DatabaseOperations(BaseDatabaseOperations): def date_extract_sql(self, lookup_type, field_name): # sqlite doesn't support extract, so we fake it with the user-defined # function django_extract that's registered in connect(). return 'django_extract("%s", %s)' % (lookup_type.lower(), field_name) def date_trunc_sql(self, lookup_type, field_name): # sqlite doesn't support DATE_TRUNC, so we fake it with a user-defined # function django_date_trunc that's registered in connect(). return 'django_date_trunc("%s", %s)' % (lookup_type.lower(), field_name)
try: import decimal except ImportError: from django.utils import _decimal as decimal # for Python 2.3 DatabaseError = Database.DatabaseError IntegrityError = Database.IntegrityError Database.register_converter("bool", lambda s: str(s) == '1') Database.register_converter("time", util.typecast_time) Database.register_converter("date", util.typecast_date) Database.register_converter("datetime", util.typecast_timestamp) Database.register_converter("timestamp", util.typecast_timestamp) Database.register_converter("TIMESTAMP", util.typecast_timestamp) Database.register_converter("decimal", util.typecast_decimal) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) if Database.version_info >= (2, 4, 1): # Starting in 2.4.1, the str type is not accepted anymore, therefore, # we convert all str objects to Unicode # As registering a adapter for a primitive type causes a small # slow-down, this adapter is only registered for sqlite3 versions # needing it. Database.register_adapter(str, lambda s: s.decode('utf-8')) class DatabaseFeatures(BaseDatabaseFeatures): # SQLite cannot handle us only partially reading from a cursor's result set # and then writing the same rows to the database in another cursor. This # setting ensures we always read result sets fully into memory all in one # go. can_use_chunked_reads = False
try: import decimal except ImportError: from django.utils import _decimal as decimal # for Python 2.3 DatabaseError = Database.DatabaseError IntegrityError = Database.IntegrityError Database.register_converter("bool", lambda s: str(s) == '1') Database.register_converter("time", util.typecast_time) Database.register_converter("date", util.typecast_date) Database.register_converter("datetime", util.typecast_timestamp) Database.register_converter("timestamp", util.typecast_timestamp) Database.register_converter("TIMESTAMP", util.typecast_timestamp) Database.register_converter("decimal", util.typecast_decimal) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) if Database.version_info >= (2,4,1): # Starting in 2.4.1, the str type is not accepted anymore, therefore, # we convert all str objects to Unicode # As registering a adapter for a primitive type causes a small # slow-down, this adapter is only registered for sqlite3 versions # needing it. Database.register_adapter(str, lambda s:s.decode('utf-8')) class DatabaseFeatures(BaseDatabaseFeatures): # SQLite cannot handle us only partially reading from a cursor's result set # and then writing the same rows to the database in another cursor. This # setting ensures we always read result sets fully into memory all in one # go. can_use_chunked_reads = False
def list_aggregate(function): """ Return an aggregate class that accumulates values in a list and applies the provided function to the data. """ return type('ListAggregate', (list,), {'finalize': function, 'step': list.append}) Database.register_converter("bool", b'1'.__eq__) Database.register_converter("time", decoder(parse_time)) Database.register_converter("datetime", decoder(parse_datetime)) Database.register_converter("timestamp", decoder(parse_datetime)) Database.register_converter("TIMESTAMP", decoder(parse_datetime)) Database.register_adapter(decimal.Decimal, str) class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'sqlite' display_name = 'SQLite' # SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. data_types = { 'AutoField': 'integer', 'BigAutoField': 'integer', 'BinaryField': 'BLOB', 'BooleanField': 'bool', 'CharField': 'varchar(%(max_length)s)', 'DateField': 'date',
def __init__(self, databaseDir): self.dataBasePath = os.path.join(databaseDir, 'MyGames.db') sqlite.register_adapter(str, lambda s:s.decode('utf-8')) #use scripts home for reading SQL files self.sqlDir = os.path.join(util.RCBHOME, 'resources', 'database')
#DATABASE = '/tmp/mini_api.db' DATABASES = 'DATABASE0','DATABASE1','DATABASE2' DATABASE0 = '/tmp/mini_api00.db' DATABASE1 = '/tmp/mini_api01.db' DATABASE2 = '/tmp/mini_api02.db' PER_PAGE = 30 DEBUG = True SECRET_KEY = b'_5#y2L"F4Q8z\n\xec]/' # create our little application :) app = Flask('mini_api') app.config.from_object(__name__) app.config.from_envvar('MINITWIT_SETTINGS', silent=True) sqlite3.register_converter('GUID', lambda b: uuid.UUID(bytes_le=b)) sqlite3.register_adapter(uuid.UUID, lambda u: buffer(u.bytes_le)) class FileParser(ConfigParser.ConfigParser): def as_dict(self): usermappings = {} with open('mini_api/mappings.ini', 'r') as f: for line in f: line = line.rstrip() #removes trailing whitespace and '\n' chars if "=" not in line: continue #skips blanks and comments w/o = if line.startswith("#"): continue #skips comments which contain = k, v = line.split("=", 1) usermappings[k] = v
def adapt_date(val): return val.isoformat() def adapt_datetime(val): return val.isoformat(" ") Database.register_converter("bool", b"1".__eq__) Database.register_converter("date", decoder(parse_date)) Database.register_converter("time", decoder(parse_time)) Database.register_converter("datetime", decoder(parse_datetime)) Database.register_converter("timestamp", decoder(parse_datetime)) Database.register_adapter(decimal.Decimal, str) Database.register_adapter(datetime.date, adapt_date) Database.register_adapter(datetime.datetime, adapt_datetime) class DatabaseWrapper(BaseDatabaseWrapper): vendor = "sqlite" display_name = "SQLite" # SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. data_types = { "AutoField": "integer", "BigAutoField": "integer", "BinaryField": "BLOB", "BooleanField": "bool",
import BaseHTTPServer import time,datetime,math from sqlite3 import dbapi2 as dba from aprspacket import BasicPacket from kmlconsumer import KmlPacket def adapt_datetime(ts): return time.mktime(ts.timetuple()) dba.register_adapter(datetime.datetime, adapt_datetime) HOST_NAME = '' PORT_NUMBER = 8080 HEAD="""<?xml version="1.0" encoding="UTF-8"?> <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom"> <Document> <Folder> <name>APRS To Kml</name> """ TAIL=""" </Folder> </Document> </kml> """ BODY=""" <Placemark> <name>%(fromCall)s</name> <styleUrl>output/aprssymbols/aprssymbols.kml#msn_%(style)s</styleUrl> <description><![CDATA[ <img src="output/aprssymbols/%(style)s.png" alt="%(style)s" width="40" height="40"/> <br> Station: <b>%(fromCall)s</b>
def decoder(conv_func): """ Convert bytestrings from Python's sqlite3 interface to a regular string. """ return lambda s: conv_func(s.decode()) Database.register_converter("bool", decoder(lambda s: s == '1')) Database.register_converter("time", decoder(parse_time)) Database.register_converter("date", decoder(parse_date)) Database.register_converter("datetime", decoder(parse_datetime)) Database.register_converter("timestamp", decoder(parse_datetime)) Database.register_converter("TIMESTAMP", decoder(parse_datetime)) Database.register_converter("decimal", decoder(backend_utils.typecast_decimal)) Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal) class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'sqlite' display_name = 'SQLite' # SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. data_types = { 'AutoField': 'integer', 'BigAutoField': 'integer', 'BinaryField': 'BLOB', 'BooleanField': 'bool', 'CharField': 'varchar(%(max_length)s)', 'DateField': 'date',
def check_sqlite_version(): if Database.sqlite_version_info < (3, 8, 3): raise ImproperlyConfigured( 'SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) check_sqlite_version() Database.register_converter("bool", b'1'.__eq__) Database.register_converter("time", decoder(parse_time)) Database.register_converter("datetime", decoder(parse_datetime)) Database.register_converter("timestamp", decoder(parse_datetime)) Database.register_converter("TIMESTAMP", decoder(parse_datetime)) Database.register_adapter(decimal.Decimal, str) class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'sqlite' display_name = 'SQLite' # SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. data_types = { 'AutoField': 'integer', 'BigAutoField': 'integer', 'BinaryField': 'BLOB', 'BooleanField': 'bool', 'CharField': 'varchar(%(max_length)s)', 'DateField': 'date',
try: import decimal except ImportError: from django.utils import _decimal as decimal # for Python 2.3 DatabaseError = Database.DatabaseError IntegrityError = Database.IntegrityError Database.register_converter("bool", lambda s: str(s) == '1') Database.register_converter("time", util.typecast_time) Database.register_converter("date", util.typecast_date) Database.register_converter("datetime", util.typecast_timestamp) Database.register_converter("timestamp", util.typecast_timestamp) Database.register_converter("TIMESTAMP", util.typecast_timestamp) Database.register_converter("decimal", util.typecast_decimal) Database.register_adapter(decimal.Decimal, util.rev_typecast_decimal) class DatabaseFeatures(BaseDatabaseFeatures): supports_constraints = False class DatabaseOperations(BaseDatabaseOperations): def date_extract_sql(self, lookup_type, field_name): # sqlite doesn't support extract, so we fake it with the user-defined # function django_extract that's registered in connect(). return 'django_extract("%s", %s)' % (lookup_type.lower(), field_name) def date_trunc_sql(self, lookup_type, field_name): # sqlite doesn't support DATE_TRUNC, so we fake it with a user-defined # function django_date_trunc that's registered in connect().
def decoder(conv_func): """ Convert bytestrings from Python's sqlite3 interface to a regular string. """ return lambda s: conv_func(s.decode()) Database.register_converter("bool", b'1'.__eq__) Database.register_converter("time", decoder(parse_time)) Database.register_converter("datetime", decoder(parse_datetime)) Database.register_converter("timestamp", decoder(parse_datetime)) Database.register_converter("TIMESTAMP", decoder(parse_datetime)) Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal) class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'sqlite' display_name = 'SQLite' # SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. data_types = { 'AutoField': 'integer', 'BigAutoField': 'integer', 'BinaryField': 'BLOB', 'BooleanField': 'bool', 'CharField': 'varchar(%(max_length)s)', 'DateField': 'date',
This function converts the received value to a regular string before passing it to the receiver function. """ return lambda s: conv_func(s.decode('utf-8')) Database.register_converter(str("bool"), decoder(lambda s: s == '1')) Database.register_converter(str("time"), decoder(parse_time)) Database.register_converter(str("date"), decoder(parse_date)) Database.register_converter(str("datetime"), decoder(parse_datetime)) Database.register_converter(str("timestamp"), decoder(parse_datetime)) Database.register_converter(str("TIMESTAMP"), decoder(parse_datetime)) Database.register_converter(str("decimal"), decoder(backend_utils.typecast_decimal)) Database.register_adapter(datetime.datetime, adapt_datetime_warn_on_aware_datetime) Database.register_adapter(decimal.Decimal, backend_utils.rev_typecast_decimal) if six.PY2: Database.register_adapter(str, lambda s: s.decode('utf-8')) Database.register_adapter(SafeBytes, lambda s: s.decode('utf-8')) class DatabaseWrapper(BaseDatabaseWrapper): vendor = 'sqlite' # SQLite doesn't actually support most of these types, but it "does the right # thing" given more verbose field definitions, so leave them as is so that # schema inspection is more useful. data_types = { 'AutoField': 'integer', 'BigAutoField': 'integer', 'BinaryField': 'BLOB',