Bladeren bron

initial import

Martin 9 jaren geleden
bovenliggende
commit
8393c4b7e1
6 gewijzigde bestanden met toevoegingen van 166 en 0 verwijderingen
  1. 1 0
      .gitignore
  2. 5 0
      config.py
  3. 2 0
      main.py
  4. 0 0
      util/__init__.py
  5. 126 0
      util/dbutil.py
  6. 32 0
      util/util.py

+ 1 - 0
.gitignore

@@ -58,3 +58,4 @@ docs/_build/
 # PyBuilder
 target/
 
+.vscode

+ 5 - 0
config.py

@@ -0,0 +1,5 @@
+DB_HOST = 'localhost'
+DB_USER = 'martin'
+DB_PW = 'martin'
+DB_SCHEMA = 'cryptokittens'
+DB_PORT = 3307

+ 2 - 0
main.py

@@ -0,0 +1,2 @@
+if __name__ == '__main__':
+    print 'Nothing to see here yet.'

+ 0 - 0
util/__init__.py


+ 126 - 0
util/dbutil.py

@@ -0,0 +1,126 @@
+import time
+
+import mysql.connector
+
+import config
+
+_CONN = mysql.connector.connect(user=config.DB_USER, host=config.DB_HOST, password=config.DB_PW, port=config.DB_PW, database=config.DB_SCHEMA)
+
+def get_row(q, params=None):
+    rows = get_list(q, params)
+    if rows:
+        return rows[0]
+    else:
+        return None
+
+def get_map(q, multiple_values=False, params=None):
+    if params and type(params) != tuple:
+        params = (params,)
+
+    cur = _CONN.cursor()
+    cur.execute(q, params)
+
+    res = {}
+
+    for row in cur:
+        k = row[0]
+        v = row[1:]
+        if len(v) == 1:
+            v = v[0]
+        
+        if multiple_values:
+            if k in res:
+                res[k].append(v)
+            else:
+                res[k] = [v]
+
+        else:
+            res[k] = v
+
+    cur.close()
+
+    return res
+
+def execute(q, params=None):
+    if params and type(params) != tuple:
+        params = (params,)
+
+    cur = _CONN.cursor()
+    cur.execute(q, params)
+    _CONN.commit()
+    cur.close()
+
+def get_list(q, params=None):
+    cur = _CONN.cursor()
+
+    if params and type(params) != tuple:
+        params = (params,)
+
+    cur.execute(q, params)
+
+    res = []
+    for row in cur:
+        if len(row) > 1:
+            res.append(row)
+        else:
+            res.append(row[0])
+
+    cur.close()
+
+    return res
+
+def get_list_buffered(q, batch_size=1000, timings=None):
+    # q must include $LIMIT where the limit should go
+    # for better performance, q may also be on the form select id, ... from ... order by id asc $LIMIT 
+
+    cur = _CONN.cursor()
+
+    last_id = -1
+    i = 0
+    while True:
+        t = time.time() if timings is not None else None        
+
+        if '$LAST_ID' in q:
+            cur.execute(q.replace('$LAST_ID', str(last_id)).replace('$LIMIT', 'LIMIT %i' % batch_size))
+        else:
+            cur.execute(q.replace('$LIMIT', 'LIMIT %i,%i' % (i * batch_size, batch_size)))
+
+        rows = list(cur)
+
+        if timings is not None:
+            timings['db'] += time.time() - t
+
+        for row in rows:
+            if len(row) > 1:
+                yield row
+            else:
+                yield row[0]
+            
+            last_id = row[0]
+
+        had_results = len(rows) > 0
+
+        if not had_results:
+            cur.close()
+            return
+
+        i += 1
+
+def get_set(q, params=None):
+    if params and type(params) != tuple:
+        params = (params,)
+
+    cur = _CONN.cursor()
+    cur.execute(q, params)
+
+    res = set()
+
+    for (v,) in cur:
+        res.add(v)
+
+    cur.close()
+
+    return res
+
+def close():
+    _CONN.close()

+ 32 - 0
util/util.py

@@ -0,0 +1,32 @@
+import sys
+import logging
+
+def init_logging():
+    # to debug where a log stmt is coming from, add %(pathname)s to the start
+    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s',
+                        stream = sys.stdout)
+    logging.getLogger('requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
+    logging.getLogger('test.requests.packages.urllib3.connectionpool').setLevel(logging.WARN)
+
+    '''
+    format:
+    asctime	%(asctime)s	Human-readable time when the LogRecord was created. By default this is of the form 2003-07-08 16:49:45,896 (the numbers after the comma are millisecond portion of the time).
+    created	%(created)f	Time when the LogRecord was created (as returned by time.time()).
+    exc_info	You shouldn't need to format this yourself.	Exception tuple (a la sys.exc_info) or, if no exception has occurred, None.
+    filename	%(filename)s	Filename portion of pathname.
+    funcName	%(funcName)s	Name of function containing the logging call.
+    levelname	%(levelname)s	Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
+    levelno	%(levelno)s	Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
+    lineno	%(lineno)d	Source line number where the logging call was issued (if available).
+    module	%(module)s	Module (name portion of filename).
+    msecs	%(msecs)d	Millisecond portion of the time when the LogRecord was created.
+    message	%(message)s	The logged message, computed as msg % args. This is set when Formatter.format() is invoked.
+    msg	You shouldn't need to format this yourself.	The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).
+    name	%(name)s	Name of the logger used to log the call.
+    pathname	%(pathname)s	Full pathname of the source file where the logging call was issued (if available).
+    process	%(process)d	Process ID (if available).
+    processName	%(processName)s	Process name (if available).
+    relativeCreated	%(relativeCreated)d	Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
+    thread	%(thread)d	Thread ID (if available).
+    threadName	%(threadName)s	Thread name (if available).
+    '''