def create_engine(user, password, database, host='127.0.0.1', port=3306, autocommit=False, **kw): """ db模块核心,用于数据库链接,生成全局对象engine engine 持有数据库链接 """ import MySQLdb global engine if engine is not None: raise DBError("Engine is already initialized") params = dict(user=user, passwd=password, db=database, host=host, port=port) defaults = dict(use_unicode=True, charset='utf8', autocommit=autocommit) for k, v in defaults.iteritems(): params[k] = kw.pop(k, v) params.update(kw) # params['buffered'] = True engine = _Engine(lambda: MySQLdb.connect(**params)) print engine logging.info("[ + ] init engine <%s> ok." % hex(id(engine)))
def cleanup(self): if self.connection: _connection = self.connection self.connection = None logging.info('[CONNECTION] [CLOSE] connection <%s>...' % hex(id(_connection))) _connection.close()
def cursor(self): if self.connection is None: self.connection = engine.connect() logging.info('[CONNECTION] [OPEN] connection <%s>...' % hex(id(self.connection))) return self.connection.cursor()
def __new__(cls, name, bases, attrs): if name == 'Model': return type.__new__(cls, name, bases, attrs) # store all subclass info if not hasattr(cls, 'subclasses'): cls.subclasses = {} if not name in cls.subclasses: cls.subclasses[name] = name else: logger1.warning('Redefine class: %s' % name) logger1.info('Scan ORMapping %s...' % name) mappings = dict() primary_key = None for k, v in attrs.iteritems(): if isinstance(v, Field): if not v.name: v.name = k logger1.info('[ MAPPING ] Found mapping: %s => %s' % (k, v)) if v.primary_key: if primary_key: raise PrimaryKeyException( 'Cannot define more than 1 primary key in class: %s' % name) if v.updatable: logger1.warning( 'NOTE: change primary key to non-updatable') v.updatable = False if v.nullable: logger1.warning( 'NOTE: change primary key to non-nullable') v.nullable = False primary_key = v mappings[k] = v if not primary_key: raise PrimaryKeyException('Primary key not defined in class : %s' % name) for k in mappings.iterkeys(): attrs.pop(k) if not '__table__' in attrs: attrs['__table__'] = name.lower() attrs['__mappings__'] = mappings attrs['__primary_key__'] = primary_key attrs['__sql__'] = lambda self: _gen_sql(attrs['__table__'], mappings) for trigger in _triggers: if not trigger in attrs: attrs[trigger] = None return type.__new__(cls, name, bases, attrs)
def run(self, port=9000, host='127.0.0.1', debug=False): """ 启动python自带的WSGI Server """ from wsgiref.simple_server import make_server logger1.info('application (%s) will start at %s:%s...' % (self._document_root, host, port)) server = make_server(host, port, self.get_wsgi_application(debug=debug)) server.serve_forever()
def add_module(self, mod): self._check_not_running() m = mod if type(mod) == types.ModuleType else load_module(mod) logger1.info('Add module: %s' % m.__name__) for name in dir(m): fn = getattr(m, name) if callable(fn) and hasattr(fn, '__web_route__') and hasattr(fn, '__web_method__'): self.add_url(fn)
def commit(self): global _db_ctx logging.info("[ + ] commit transaction...") try: _db_ctx.connection.commit() logging.info("[ + ] transaction ok") except: logging.warn("[ - ] commit failed, try rollback...") _db_ctx.connection.rollback() raise
def __enter__(self): global _db_ctx self.should_close_conn = False if not _db_ctx.is_init(): _db_ctx.init() self.should_close_conn = True _db_ctx.transactions += 1 logging.info("[Transaction] begin transaction.." if _db_ctx. transactions == 1 else 'join current transaction...') return self
def _update(sql, *args): """ 执行update 语句,返回update的行数 """ global _db_ctx sql = sql.replace('?', '%s') logger1.info('SQL: %s, ARGS: %s' % (sql, args)) try: cursor = _db_ctx.connection.cursor() cursor.execute(sql, args) r = cursor.rowcount return r except: raise
def add_url(self, func): """ add url func """ self._check_not_running() route = Route(func) if route.is_static: if route.method == 'GET': self._get_static[route.path] = route if route.method == 'POST': self._post_static[route.path] = route else: if route.method == 'GET': self._get_dynamic.append(route) if route.method == 'POST': self._post_dynamic.append(route) logger1.info('Add route: %s' % str(route))
def _select(sql, first, *args): """ 执行SQL, 返回结果 或者多个结果组成的列表 """ global _db_ctx sql = sql.replace('?', "%s") logger1.info('SQL: %s, ARGS: %s' % (sql, args)) try: cursor = _db_ctx.connection.cursor() cursor.execute(sql, args) if cursor.description: names = [x[0] for x in cursor.description] if first: values = cursor.fetchone() if not values: return None return Dict(names, values) return [Dict(names, x) for x in cursor.fetchall()] except: raise
def add_interceptor(self, func): self._check_not_running() self._interceptors.append(func) logger1.info('Add interceptor: %s' % str(func))
def rollback(self): global _db_ctx logging.warn('[ + ] rollback transaction...') _db_ctx.connection.rollback() logging.info('[ + ] rollback ok.')