1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
| import sys import asyncio import logging logging.basicConfig(level=logging.INFO)
import aiomysql def log(sql,args=()): logging.info('SQL:%s' %sql) @asyncio.coroutine def create_pool(loop, **kw): logging.info(' start creating database connection pool') global __pool __pool=yield from aiomysql.create_pool( host=kw.get('host','localhost'), port=kw.get('port',3306), user=kw['user'], password=kw['password'], db=kw['db'], charset=kw.get('charset','utf8'), autocommit=kw.get('autocommit',True), maxsize=kw.get('maxsize',10), minsize=kw.get('minsize',1), loop=loop ) @asyncio.coroutine def destroy_pool(): global __pool if __pool is not None : __pool.close() yield from __pool.wait_closed()
@asyncio.coroutine def select(sql, args, size=None): log(sql,args) global __pool with (yield from __pool)as conn: cur = yield from conn.cursor(aiomysql.DictCursor) yield from cur.execute(sql.replace('?', '%s'), args) if size: rs = yield from cur.fetchmany(size) else: rs = yield from cur.fetchall() yield from cur.close() logging.info('rows have returned %s' %len(rs)) return rs
@asyncio.coroutine def execute(sql,args, autocommit=True): log(sql) global __pool with (yield from __pool) as conn: try: cur = yield from conn.cursor() yield from cur.execute(sql.replace('?', '%s'), args) yield from conn.commit() affected_line=cur.rowcount yield from cur.close() print('execute : ', affected_line) except BaseException as e: raise return affected_line
def create_args_string(num): lol=[] for n in range(num): lol.append('?') return (','.join(lol))
class Field(object): def __init__(self, name, column_type, primary__key, default): self.name = name self.column_type=column_type self.primary_key=primary__key self.default=default def __str__(self): return "<%s , %s , %s>" %(self.__class__.__name__, self.name, self.column_type)
class StringField(Field): def __init__(self, name=None, primary_key=False, default=None, ddl='varchar(100)'): super().__init__(name,ddl,primary_key,default)
class BooleanField(Field): def __init__(self, name=None, default=None): super().__init__(name,'Boolean',False, default)
class IntegerField(Field): def __init__(self, name=None, primary_key=False, default=0): super().__init__(name, 'int', primary_key, default) class FloatField(Field): def __init__(self, name=None, primary_key=False,default=0.0): super().__init__(name, 'float', primary_key, default) class TextField(Field): def __init__(self, name=None, default=None): super().__init__(name,'text',False, default)
class ModelMetaclass(type): def __new__(cls, name, bases, attrs): if name=='Model': return type.__new__(cls, name, bases, attrs) table_name=attrs.get('__table__', None) or name logging.info('found table: %s (table: %s) ' %(name,table_name )) mappings=dict() fields=[] primaryKey=None for k, v in attrs.items(): if isinstance(v, Field): logging.info('Found mapping %s===>%s' %(k, v)) mappings[k] = v if v.primary_key: logging.info('fond primary key hahaha %s'%k) if primaryKey: raise RuntimeError('Duplicated key for field') primaryKey=k else: fields.append(k) if not primaryKey: raise RuntimeError('Primary key not found!') for k in mappings.keys(): attrs.pop(k) escaped_fields=list(map(lambda f:'`%s`' %f, fields)) attrs['__mappings__']=mappings attrs['__table__']=table_name attrs['__primary_key__']=primaryKey attrs['__fields__']=fields attrs['__select__']='select `%s`, %s from `%s` '%(primaryKey,', '.join(escaped_fields), table_name) attrs['__insert__'] = 'insert into `%s` (%s, `%s`) values (%s) ' %(table_name, ', '.join(escaped_fields), primaryKey, create_args_string(len(escaped_fields)+1)) attrs['__update__']='update `%s` set %s where `%s` = ?' %(table_name, ', '.join(map(lambda f:'`%s`=?' % (mappings.get(f).name or f), fields)), primaryKey) attrs['__delete__']='delete `%s` where `%s`=?' %(table_name, primaryKey) return type.__new__(cls, name, bases, attrs)
class Model(dict,metaclass=ModelMetaclass): def __init__(self, **kw): super(Model,self).__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError("'Model' object have no attribution: %s"% key) def __setattr__(self, key, value): self[key] =value def getValue(self, key): return getattr(self, key, None) def getValueOrDefault(self, key): value=getattr(self, key , None) if value is None: field = self.__mappings__[key] if field.default is not None: value = field.default() if callable(field.default) else field.default logging.info('using default value for %s : %s ' % (key, str(value))) setattr(self, key, value) return value @classmethod @asyncio.coroutine def find_all(cls, where=None, args=None, **kw): sql = [cls.__select__] if where: sql.append('where') sql.append(where) if args is None: args = [] orderBy = kw.get('orderBy', None) if orderBy: sql.append('order by') sql.append(orderBy) limit = kw.get('limit', None) if limit is not None: sql.append('limit') if isinstance(limit, int): sql.append('?') args.append(limit) elif isinstance(limit, tuple) and len(limit) ==2: sql.append('?,?') args.extend(limit) else: raise ValueError('Invalid limit value : %s '%str(limit)) rs = yield from select(' '.join(sql),args) return [cls(**r) for r in rs] @classmethod @asyncio.coroutine def findNumber(cls, selectField, where=None, args=None): '''find number by select and where.''' sql = ['select %s __num__ from `%s`' %(selectField, cls.__table__)] if where: sql.append('where') sql.append(where) rs = yield from select(' '.join(sql), args, 1) if len(rs) == 0: return None return rs[0]['__num__'] @classmethod @asyncio.coroutine def find(cls, primarykey): '''find object by primary key''' rs = yield from select('%s where `%s`=?' %(cls.__select__, cls.__primary_key__), [primarykey], 1) if len(rs) == 0: return None return cls(**rs[0]) @classmethod @asyncio.coroutine def findAll(cls, **kw): rs = [] if len(kw) == 0: rs = yield from select(cls.__select__, None) else: args=[] values=[] for k, v in kw.items(): args.append('%s=?' % k ) values.append(v) rs = yield from select('%s where %s ' % (cls.__select__, ' and '.join(args)), values) return rs @asyncio.coroutine def save(self): args = list(map(self.getValueOrDefault, self.__fields__)) print('save:%s' % args) args.append(self.getValueOrDefault(self.__primary_key__)) rows = yield from execute(self.__insert__, args) if rows != 1: print(self.__insert__) logging.warning('failed to insert record: affected rows: %s' %rows) @asyncio.coroutine def update(self): args = list(map(self.getValue, self.__fields__)) args.append(self.getValue(self.__primary_key__)) rows = yield from execute(self.__update__, args) if rows != 1: logging.warning('failed to update record: affected rows: %s'%rows) @asyncio.coroutine def remove(self): args = [self.getValue(self.__primary_key__)] rows = yield from execute(self.__updata__, args) if rows != 1: logging.warning('failed to remove by primary key: affected rows: %s' %rows) if __name__=="__main__": class User(Model): id = IntegerField('id',primary_key=True) name = StringField('username') email = StringField('email') password = StringField('password') loop = asyncio.get_event_loop() @asyncio.coroutine def test(): yield from create_pool(loop=loop,host='localhost', port=3308, user='sly', password='070801382', db='test') user = User(id=8, name='sly', email='slysly759@gmail.com', password='fuckblog') yield from user.save() r = yield from User.find('11') print(r) r = yield from User.findAll() print(1, r) r = yield from User.findAll(id='12') print(2, r) yield from destroy_pool() loop.run_until_complete(test()) loop.close() if loop.is_closed(): sys.exit(0)
|