def project_delete(db, project): """ Delete project. Also delete all related categories and events. """ haystack = { 'project_id': project['_id'] } query = "DELETE FROM projects WHERE _id=%(project_id)s" try: yield momoko.Op( db.execute, query, haystack ) except Exception as e: on_error(e) query = "DELETE FROM categories WHERE project_id=%(project_id)s" try: yield momoko.Op( db.execute, query, haystack ) except Exception as e: on_error(e) raise Return((True, None))
def add_stats(self, name, delta=1, oid=0): user = self.get_current_user() if user: uid = user['uid'] else: uid = 0 sql = '''select id from ksforum.forum_stats where name=%(name)s and uid=%(uid)s limit 1 ''' params = {'uid': uid, 'name': name, 'delta': delta, 'oid': oid} cursor = yield momoko.Op(self.db.execute, sql, params) record = cursor.fetchone() if record: sql = '''update ksforum.forum_stats set total=total+%(delta)s, updated_at=%(updated_at)s where name=%(name)s and oid=%(oid)s and uid=%(uid)s ''' params = { 'uid': uid, 'name': name, 'delta': delta, 'oid': oid, 'updated_at': datetime.datetime.utcnow() } cursor = yield momoko.Op(self.db.execute, sql, params) else: sql = '''insert into ksforum.forum_stats (uid, name, oid, total) values(%(uid)s, %(name)s, %(oid)s, %(delta)s) ''' params = {'uid': uid, 'name': name, 'delta': delta, 'oid': oid} cursor = yield momoko.Op(self.db.execute, sql, params) raise gen.Return(None)
def create_relation_projects(): table = u'projects' print u'creating {} relation'.format(table) conn = PSQLClient.get_client() query = prepare_creation(table) yield momoko.Op(conn.execute, query) # INDEXES: yield momoko.Op( conn.execute, u"UPDATE projects SET title_tsvector = (to_tsvector('international', title));" ) yield momoko.Op( conn.execute, u"UPDATE projects SET description_short_tsvector" u" = (to_tsvector('international', description_short));") yield momoko.Op( conn.execute, u"CREATE INDEX title_idx ON projects " u"USING GIN (title_tsvector);") yield momoko.Op( conn.execute, u"CREATE INDEX description_short_idx ON projects " u"USING GIN (description_short_tsvector);") yield momoko.Op(conn.execute, u"CREATE INDEX tags_idx ON projects(tags);") yield momoko.Op( conn.execute, u"""DROP FUNCTION IF EXISTS project_vector_update() CASCADE;""") yield momoko.Op( conn.execute, u"""DROP TRIGGER IF EXISTS tsvectorupdate on projects CASCADE;""") yield momoko.Op( conn.execute, u"""CREATE FUNCTION project_vector_update() RETURNS TRIGGER AS $$ BEGIN IF TG_OP = 'INSERT' THEN new.title_tsvector = to_tsvector('international', COALESCE(NEW.title, '')); new.description_short_tsvector = to_tsvector('international', COALESCE(NEW.description_short, '')); END IF; IF TG_OP = 'UPDATE' THEN IF NEW.title <> OLD.title THEN new.title_tsvector = to_tsvector('international', COALESCE(NEW.title, '')); END IF; IF NEW.description_short <> OLD.description_short THEN new.description_short_tsvector = to_tsvector('international', COALESCE(NEW.description_short, '')); END IF; END IF; RETURN NEW; END $$ LANGUAGE 'plpgsql';""") yield momoko.Op( conn.execute, u"CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE " u"ON projects FOR EACH ROW EXECUTE PROCEDURE project_vector_update();")
def post(self, user=None): # Validate arguments. if not user: raise HTTPError(401, 'Not authorized.') id = int(self.get_argument('id')) permissions = [(str(perm[0]), perm[1]) for perm in json.loads(self.get_argument('permissions')) ] # Check if user owns a non-dir asset with given id cursor = yield momoko.Op( self.db.execute, '''SELECT 1 FROM assets WHERE type <> %s AND owner = %s AND id = %s ''', ('dir', user.id, id)) data = cursor.fetchone() if not data: raise HTTPError(404, 'Asset not owned by user.') if len(permissions) > 0: # get owner email cursor = yield momoko.Op( self.db.execute, '''SELECT email FROM users WHERE id = %s ''', (user.id, )) data = cursor.fetchone() if not data: raise HTTPError(400, 'Permissions setting failed.') ownerEmail = data[0] # Delete previous permissions cursor = yield momoko.Op( self.db.execute, '''DELETE FROM permissions WHERE asset_id = %s ''', (id, )) # Insert new permissions if needed if len(permissions) > 0: permissions.append((ownerEmail, True)) queries = [] for perm in permissions: queries.append( ('''INSERT INTO permissions (asset_id, user_id, write) SELECT %s AS asset_id, id, %s AS write FROM users WHERE email = %s RETURNING user_id ''', (id, perm[1], perm[0]))) cursors = yield momoko.Op(self.db.transaction, tuple(queries)) for x in range(len(permissions)): data = cursors[x].fetchone() if not data: raise HTTPError(400, 'Permissions setting failed.') self.finish()
def create_relation_schools(): table = u'schools' print u'creating {} relation'.format(table) conn = PSQLClient.get_client() query = prepare_creation(table) yield momoko.Op(conn.execute, query) yield momoko.Op(conn.execute, u"CREATE INDEX schools_title_idx ON schools (title);")
def get(self, user=None): """Retrieves the public space.""" # Validate arguments. if not user: # Set special id for not logged in users user = Account(-1) # Initialise public space data. data = (-1, 'Public') #Fetch assets shared with user with write perm. cursor = yield momoko.Op( self.db.execute, '''SELECT asset_id FROM permissions WHERE user_id = %s AND write = %s ''', (user.id, True)) assetsWrite = [asset[0] for asset in cursor.fetchall()] # Fetch information about public assets. cursor = yield momoko.Op( self.db.execute, '''SELECT assets.id, assets.name, assets.type, assets.preview, assets.owner, users.email FROM assets INNER JOIN users ON assets.owner = users.id WHERE public = %s ''', (True, )) # Return JSON answer. self.write_json({ 'id': data[0], 'name': data[1], 'owner': True, 'write': True, 'public': False, 'data': [{ 'id': item[0], 'name': item[1], 'type': item[2], 'preview': str(item[3]) if item[3] else '', 'public': True, 'owner': item[4] == int(user.id), 'write': item[4] == int(user.id) or item[0] in assetsWrite, 'email': 'You' if item[4] == int(user.id) else item[5] } for item in cursor.fetchall()] }) self.finish()
def create_relation_vacancies(): table = u'vacancies' print u'creating {} relation'.format(table) conn = PSQLClient.get_client() query = prepare_creation(table) yield momoko.Op(conn.execute, query) yield momoko.Op( conn.execute, u"UPDATE vacancies SET vacancy_name_tsvector = (to_tsvector('international'," u"vacancy_name));") yield momoko.Op( conn.execute, u"UPDATE vacancies SET vacancy_description_tsvector" u" = (to_tsvector('international', description));") yield momoko.Op( conn.execute, u"CREATE INDEX vacancy_name_idx ON vacancies " u"USING GIN(vacancy_name_tsvector);") yield momoko.Op( conn.execute, u"CREATE INDEX vacancy_description_idx ON vacancies " u"USING GIN(vacancy_description_tsvector);") yield momoko.Op( conn.execute, u"""DROP FUNCTION IF EXISTS vacancy_vector_update() CASCADE;""") yield momoko.Op( conn.execute, u"""DROP TRIGGER IF EXISTS tsvectorupdate on vacancies CASCADE;""") yield momoko.Op( conn.execute, u"""CREATE FUNCTION vacancy_vector_update() RETURNS TRIGGER AS $$ BEGIN IF TG_OP = 'INSERT' THEN new.vacancy_name_tsvector = to_tsvector('international', COALESCE(NEW.vacancy_name, '')); new.vacancy_description_tsvector = to_tsvector('international', COALESCE(NEW.description, '')); END IF; IF TG_OP = 'UPDATE' THEN IF NEW.vacancy_name <> OLD.vacancy_name THEN new.vacancy_name_tsvector = to_tsvector('international', COALESCE(NEW.vacancy_name, '')); END IF; IF NEW.description <> OLD.description THEN new.vacancy_description_tsvector = to_tsvector('international', COALESCE(NEW.description, '')); END IF; END IF; RETURN NEW; END $$ LANGUAGE 'plpgsql';""") yield momoko.Op( conn.execute, u"CREATE TRIGGER tsvectorupdate BEFORE INSERT OR UPDATE " u"ON vacancies FOR EACH ROW EXECUTE PROCEDURE vacancy_vector_update();" )
def post(self): errors = [] action = self.get_argument('action', '') user = self.get_current_user() if user: usersettings = self.DEFAULT_SETTINGS else: self.redirect('/user/login') if action == 'profile': logger.debug('current user:%s, type:%s', user, type(user)) nickname = self.get_argument('nickname', '').strip() if nickname: sql = '''update ksforum.forum_users set nickname=%(nickname)s where id=%(uid)s''' r = yield momoko.Op(self.db.execute, sql, { 'uid': user['uid'], 'nickname': nickname }) elif action == 'modifypassword': oldpassword = self.get_argument('password0', '').strip() newpassword1 = self.get_argument('password1', '').strip() newpassword2 = self.get_argument('password2', '').strip() if oldpassword and (newpassword1 == newpassword2): sql = '''update ksforum.forum_users set nickname=%(nickname)s where id=%(uid)s''' r = yield momoko.Op(self.db.execute, sql, { 'uid': user['uid'], 'nickname': nickname }) r = yield self.update_password(user['uid'], oldpassword, newpassword1) else: pass if errors: error_msg = tornado.escape.url_escape( "Login Failed, username and password not match.") next = tornado.escape.url_escape('/user/home') self.redirect("/user/login?next=%s&error=%s" % (next, error_msg)) else: record = yield self.get_user(user['uid']) user = { 'uid': record.id, 'email': record.email, 'username': record.username, 'nickname': record.nickname, 'retcode': 0 } self.set_current_user(user) self.redirect("/user/home")
def add_track(self, path, host=None, ua=None): user = self.get_current_user() uid = 0 if user: uid = user['uid'] hostid = 0 if host: sql = '''select id from ksforum.forum_hosts where ip=%(ip)s limit 1 ''' params = {'ip': host} cursor = yield momoko.Op(self.db.execute, sql, params) record = cursor.fetchone() if record: hostid = record.id else: sql = '''insert into ksforum.forum_hosts (id, ip) values(DEFAULT,%(ip)s) RETURNING id ''' params = {'ip': host} cursor = yield momoko.Op(self.db.execute, sql, params) record = cursor.fetchone() hostid = record.id uaid = 0 if ua: sql = '''select id from ksforum.forum_useragents where agent=%(ua)s limit 1 ''' params = {'ua': ua} cursor = yield momoko.Op(self.db.execute, sql, params) record = cursor.fetchone() if record: uaid = record.id else: sql = '''insert into ksforum.forum_useragents (id, agent) values(DEFAULT,%(agent)s) RETURNING id ''' params = {'agent': ua} cursor = yield momoko.Op(self.db.execute, sql, params) record = cursor.fetchone() uaid = record.id sql = '''insert into ksforum.forum_visits (uid, path, hostid, uaid) values(%(uid)s, %(path)s, %(hostid)s, %(uaid)s) ''' params = {'uid': uid, 'path': path, 'hostid': hostid, 'uaid': uaid} cursor = yield momoko.Op(self.db.execute, sql, params) raise gen.Return(None)
def get(self): cursor1, cursor2, cursor3 = yield [ momoko.Op(self.db.execute, 'SELECT 1;'), momoko.Op(self.db.mogrify, 'SELECT 2;'), momoko.Op(self.db.execute, 'SELECT %s;', (3*1,)) ] self.write('Query 1 results: %s<br>' % cursor1.fetchall()) self.write('Query 2 results: %s<br>' % cursor2) self.write('Query 3 results: %s' % cursor3.fetchall()) self.finish()
def create_relation_cities(): table = u'cities' print u'creating {} relation'.format(table) conn = PSQLClient.get_client() query = prepare_creation(table) yield momoko.Op(conn.execute, query) yield momoko.Op(conn.execute, u"CREATE INDEX cities_region_idx ON cities (region);") yield momoko.Op(conn.execute, u"CREATE INDEX cities_area_idx ON cities (area);") yield momoko.Op(conn.execute, u"CREATE INDEX cities_title_idx ON cities (title);")
def create_relation_countries(): table = u'countries' print u'creating {} relation'.format(table) conn = PSQLClient.get_client() query = prepare_creation(table) yield momoko.Op(conn.execute, query) yield momoko.Op( conn.execute, u"CREATE INDEX countries_title_ru_idx ON countries (title_ru);") yield momoko.Op( conn.execute, u"CREATE INDEX countries_title_en_idx ON countries (title_en);")
def get(self): if enable_hstore: try: cursor = yield momoko.Op(self.db.execute, "SELECT 'a=>b, c=>d'::hstore;") self.write('Query results: %s<br>' % cursor.fetchall()) cursor = yield momoko.Op(self.db.execute, "SELECT %s;", ({'e': 'f', 'g': 'h'},)) self.write('Query results: %s<br>' % cursor.fetchall()) except Exception as error: self.write(str(error)) else: self.write('hstore is not enabled') self.finish()
def namespace_create(db, project, **kwargs): to_insert = { '_id': str(ObjectId()), 'project_id': project['_id'], 'name': kwargs['name'], 'publish': kwargs['publish'], 'is_watching': kwargs['is_watching'], 'presence': kwargs['presence'], 'history': kwargs['history'], 'history_size': kwargs['history_size'], 'is_private': kwargs['is_private'], 'auth_address': kwargs['auth_address'], 'join_leave': kwargs['join_leave'] } query = "INSERT INTO namespaces (_id, project_id, name, publish, " \ "is_watching, presence, history, history_size, is_private, " \ "auth_address, join_leave) VALUES (%(_id)s, %(project_id)s, %(name)s, " \ "%(publish)s, %(is_watching)s, %(presence)s, " \ "%(history)s, %(history_size)s, %(is_private)s, %(auth_address)s, " \ "%(join_leave)s)" try: yield momoko.Op(db.execute, query, to_insert) except Exception as e: on_error(e) else: raise Return((to_insert, None))
def namespace_edit(db, namespace, **kwargs): """ Edit project """ to_update = { '_id': namespace['_id'], 'name': kwargs['name'], 'publish': kwargs['publish'], 'is_watching': kwargs['is_watching'], 'presence': kwargs['presence'], 'history': kwargs['history'], 'history_size': kwargs['history_size'], 'is_private': kwargs['is_private'], 'auth_address': kwargs['auth_address'], 'join_leave': kwargs['join_leave'] } query = "UPDATE namespaces SET name=%(name)s, publish=%(publish)s, " \ "is_watching=%(is_watching)s, presence=%(presence)s, " \ "history=%(history)s, history_size=%(history_size)s, " \ "is_private=%(is_private)s, auth_address=%(auth_address)s, " \ "join_leave=%(join_leave)s WHERE _id=%(_id)s" try: yield momoko.Op(db.execute, query, to_update) except Exception as e: on_error(e) else: raise Return((to_update, None))
def is_writeable(self): """Return None if no permission, False if read-only, True if writeable.""" # Fetch data from the asset and permission table. # The write flag will have 3 possible values: None, True, False cursor = yield momoko.Op( self.db.execute, '''SELECT id, public, owner, write FROM assets LEFT OUTER JOIN permissions ON permissions.asset_id = assets.id WHERE assets.id = %(id)s AND assets.type = 'scene' AND (permissions.user_id = %(user)s OR permissions.user_id is NULL OR %(user)s IS NULL) ''', { 'id': self.scene_id, 'user': self.user.id if self.user else None }) data = cursor.fetchone() if not data: raise HTTPError(404, 'Asset not found.') if self.user and data['owner'] == self.user.id: raise Return(True) elif data['write'] is None: if not data['public']: raise Return(None) else: raise Return(False) else: raise Return(self.user is not None and data['write'])
def project_edit(db, project, **kwargs): """ Edit project """ to_update = { '_id': extract_obj_id(project), 'name': kwargs['name'], 'display_name': kwargs['display_name'], 'auth_address': kwargs['auth_address'], 'max_auth_attempts': kwargs['max_auth_attempts'], 'back_off_interval': kwargs['back_off_interval'], 'back_off_max_timeout': kwargs['back_off_max_timeout'], 'default_namespace': kwargs['default_namespace'] } query = "UPDATE projects SET name=%(name)s, display_name=%(display_name)s, " \ "auth_address=%(auth_address)s, " \ "max_auth_attempts=%(max_auth_attempts)s, back_off_interval=%(back_off_interval)s, " \ "back_off_max_timeout=%(back_off_max_timeout)s, default_namespace=%(default_namespace)s WHERE " \ "_id=%(_id)s" try: yield momoko.Op(db.execute, query, to_update) except Exception as e: on_error(e) else: raise Return((to_update, None))
def delete_table(self): sql = """ DROP TABLE IF EXISTS users_user; DROP SEQUENCE IF EXISTS user_id; """ cursor = yield momoko.Op(self.db.execute, sql) return cursor
def update_scene_(self, func): """Helper to update a scene.""" #yield Task(self.lock.acquire, blocking=True) # Retrieve the scene object. data = self.redis.hmget('scene:%s' % self.scene_id, ['name', 'users']) if data: scene = Scene(self.scene_id, name=data[0], users=json.loads(data[1] or '[]')) else: cursor = yield momoko.Op( self.db.execute, '''SELECT name FROM assets WHERE id = %(id)s''', {'id': self.scene_id}) scene = Scene(self.scene_id, name=cursor.fetchone()['name'], users=[]) # Apply changes. func(scene) # Store the modified scene. self.redis.hmset('scene:%s' % self.scene_id, { 'name': scene.name, 'users': json.dumps(scene.users) }) raise Return(scene)
def save(self, conn, update=True, fields=None, columns=None): if fields: data = {k: getattr(self, k) for k in fields if hasattr(self, k)} else: data = self._get_editable_attrs() if set(self.JSON_FIELDS) & set(data.keys()): for f in self.JSON_FIELDS: v = data.get(f) if not v: continue [k.update(id=generate_id()) for k in v if not k.get(u'id')] if update: sql_query = get_update_query(self.TABLE, data, where_params=dict(id=self.id), editable_columns=columns or self.EDITABLE_FIELDS) else: sql_query = get_insert_query(self.TABLE, data, self.CREATE_FIELDS) try: cursor = yield momoko.Op(conn.execute, sql_query) self.id = cursor.fetchone()[0] except Exception, ex: raise PSQLException(ex)
def get_all_json(cls, conn, columns=None): if not columns: columns = list( set(MODELS[cls.TABLE].keys()) - set(cls.SYSTEM_INFO)) sql_query = get_select_query(cls.TABLE, columns) cursor = yield momoko.Op(conn.execute, sql_query) data = cursor.fetchall() data_list = [] for d in data: data_dict = {} for i, k in enumerate(columns): if not d[i]: continue v = d[i] restore = MODELS[cls.TABLE][k].restore if restore: try: v = restore(v) except: pass to_json = MODELS[cls.TABLE][k].to_json if to_json: v = to_json(v) data_dict.update({k: v}) data_list.append(data_dict) logging.info(data_list) raise gen.Return(data_list)
def get(self): try: connection = yield momoko.Op(self.db.getconn) with self.db.manage(connection): for i in range(5): if self.http_connection_closed: break cursor = yield momoko.Op(connection.execute, 'SELECT pg_sleep(1);') self.write('Query %d results: %s<br>\n' % (i + 1, cursor.fetchall())) self.flush() except Exception as error: self.write(str(error)) self.finish()
def init(): """ Helper to call db code after ioloop has started """ print("Executing initialization") print(db.dsn) cursor = yield momoko.Op( db.execute, """ DROP SCHEMA public CASCADE; CREATE SCHEMA public; CREATE TABLE game ( game_id text PRIMARY KEY, players integer, state bytea, timestamp timestamp ); CREATE UNIQUE INDEX ix_game_id ON game (game_id); CREATE INDEX ix_timestamp ON game (timestamp); """) try: print(cursor.fetchall()) except psycopg2.ProgrammingError: pass io = ioloop.IOLoop.instance() io.stop()
def project_create(db, **kwargs): to_insert = { '_id': str(ObjectId()), 'name': kwargs['name'], 'display_name': kwargs['display_name'], 'auth_address': kwargs['auth_address'], 'max_auth_attempts': kwargs['max_auth_attempts'], 'back_off_interval': kwargs['back_off_interval'], 'back_off_max_timeout': kwargs['back_off_max_timeout'], 'secret_key': uuid.uuid4().hex, 'default_namespace': None } query = "INSERT INTO projects (_id, name, display_name, " \ "auth_address, max_auth_attempts, back_off_interval, " \ "back_off_max_timeout, secret_key, default_namespace) " \ "VALUES (%(_id)s, %(name)s, %(display_name)s, " \ "%(auth_address)s, %(max_auth_attempts)s, %(back_off_interval)s, " \ "%(back_off_max_timeout)s, %(secret_key)s, %(default_namespace)s)" try: yield momoko.Op(db.execute, query, to_insert) except Exception as e: on_error(e) else: raise Return((to_insert, None))
def get(self): username = None serverseedhash = None wallet_address = None if self.current_user: username = tornado.escape.json_decode(self.current_user).lower() serverseedhash = self.server_variables.hashedserverseed query = 'select wallet_address from users where username = lower(%s);' try: cursor = yield momoko.Op( self.db.execute, query, (username, ), cursor_factory=psycopg2.extras.DictCursor) wallet_address = cursor.fetchone()['wallet_address'] self.set_status(200) except Exception: logging.exception("Username: " + username) self.render('index.html', username=username, depositaddress=wallet_address, houseedge=self.server_variables.houseedge, jscode=None)
def post(self): username = json.loads(self.get_argument("username", None)).lower() password = json.loads(self.get_argument("password", None)) if not username or not password: self.set_status(401, "No username or password.") self.finish() return query = 'select hashed_password, salt from users where username = lower(%s);' try: cursor = yield momoko.Op(self.db.execute, query, (username, ), cursor_factory=psycopg2.extras.DictCursor) data = cursor.fetchone() auth = verify_password(password, data['hashed_password'], data['salt']) if auth: set_current_user(self, username) self.set_status(200, "%s authenticated." % (username)) else: self.set_status(401, "Wrong username or password.") except Exception: logging.exception("Username: " + username) self.set_status(400) finally: self.finish()
def get(self): imgid = self.get_argument('md5', '') sign = self.get_argument('sign', '') if sign != hashlib.md5(imgid + self.application.salt).hexdigest(): self.write('forbidden') self.set_status(403) self.finish() else: try: cursor = yield momoko.Op(self.db.execute, "select size, length, width, fmat from image where imgid = '%s'" % (imgid) ) except (psycopg2.Warning, psycopg2.Error) as error: self.write(str(error)) try: img = cursor.fetchone() size, length, width, fmat = img except: json_data = { 'imgid' : imgid, 'result' : 'not found' } return self.write(tornado.escape.json_encode(json_data)) else: json_data = { 'size' : size, 'length':length, 'width':width, 'fmat':fmat } self.set_header('Content-Type', 'text/javascript') return self.write(tornado.escape.json_encode(json_data))
def get(self): search_param = self.get_argument("q", None) output = self.get_argument("output", None) if search_param is None: self.render("bets.html", results=None) return if search_param.isdigit(): query = 'select bet_id, username, bet_time, bet_amount, payout, game, roll, profit, result, server_seed, client_seed from bets where bet_id = %s AND server_seed != %s order by bet_id desc;' else: query = 'select bet_id, username, bet_time, bet_amount, payout, game, roll, profit, result, server_seed, client_seed from bets where username = lower(%s) AND server_seed != %s order by bet_id desc;' try: cursor = yield momoko.Op( self.db.execute, query, (search_param, self.server_variables.serverseed), cursor_factory=psycopg2.extras.DictCursor) data = [dict((cursor.description[i][0], value) \ for i, value in enumerate(row)) for row in cursor.fetchall()] msg = '{"searchResults":%s}' % (json.dumps(data, default=json_serial)) if output == "json": self.write(msg) self.finish() else: self.render("bets.html", results=json.dumps(data, default=json_serial)) except Exception: logging.exception("Search Parameter: " + search_param) self.set_status(400, "Unknown search parameter.")
def get(self): imgid = self.get_argument('md5', '') sign = self.get_argument('sign', '') if sign != hashlib.md5(imgid + self.application.salt).hexdigest(): self.set_status(403) return self.write('forbidden') else: try: cursor = yield momoko.Op(self.db.execute, "select remote_file_id, fmat from image where imgid='%s'" % (imgid, )) except (psycopg2.Warning, psycopg2.Error) as error: self.set_status(500) logging.info('%s : download image: when lookup table, error ocurs' % (time.ctime())) return try: img = cursor.fetchone() remote_file_id, fmat = img ret = fdfsclient.download_to_buffer(remote_file_id) except: self.set_status(500) logging.info('%s : fdfs_client download image error' % (time.ctime())) return else: img_build = Image.open(cStringIO.StringIO(ret['Content'])) o = io.BytesIO() img_build.save(o, format=fmat) s = o.getvalue() self.set_header('Content-Type', 'image/%s' % fmat) self.set_header('Content-length', len(s)) return self.write(s)
def last_insert_id(self, cursor, model, callback=None): seq = model._meta.primary_key.sequence if seq: sql = "SELECT CURRVAL('\"%s\"')" % (seq) cursor = yield momoko.Op(self.get_conn().execute, sql) callback(cursor.fetchone()[0]) return elif model._meta.auto_increment: sql = "SELECT CURRVAL('\"%s_%s_seq\"')" % ( model._meta.db_table, model._meta.primary_key.db_column) cursor = yield momoko.Op(self.get_conn().execute, sql) callback(cursor.fetchone()[0]) return callback(None) return