def api_delete_page(): i = ctx.request.input(id='') if not i.id: raise APIValueError('id', 'id cannot be empty.') page = _get_page(i.id) db.update('delete from pages where id=?', i.id) return True
def result(): if request.method == 'GET': return '<html><h1>404!!你访问的页面不存在</h1><body></body></html>' # print request.form studentID = session.get('studentID') score = [0, 0] with db.transaction(): for x in request.form: quesID = re.match('ques([0-9]*).*', x).group(1) # quesID = int(quesID) + 1 ans = request.form.getlist(x) if len(ans) > 1: ans = ';'.join(ans) else: ans = ans[0] # print studentID, quesID, ans stu_ques = student_ques(studentID=studentID, questionID=quesID, answer=ans) # print stu_ques try: stu_ques.insert() except Exception, e: # print e.message, e if 'Duplicate entry' in str(e): break else: return '1' s = count_score(quesID, ans) score[0] += s[0] score[1] += s[1] db.update(u'update `students` set finished = 1, ' 'score_part2 = %d, score_part3 = %d ' 'where studentID = %s' % (score[0], score[1], studentID))
def delete_attachment(attr_id): att = db.select_one('select * from attachments where id=?', attr_id) if att.website_id != ctx.website.id: raise APIPermissionError('Cannot delete resource that not belong to current website.') # FIXME: check user_id: store.delete_resources(attr_id) db.update('delete from attachments where id=?', attr_id)
def delete(self): self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk), ) db.update('delete from `%s` where `%s` = ?' % (self.__table__, pk), *args) return self
def delete(self): self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk), ) db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args) return self
def delete_attachment(attr_id): att = db.select_one('select * from attachments where id=?', attr_id) if att.website_id != ctx.website.id: raise APIPermissionError( 'Cannot delete resource that not belong to current website.') # FIXME: check user_id: store.delete_resources(attr_id) db.update('delete from attachments where id=?', attr_id)
def api_delete_article(): i = ctx.request.input(id='') if not i.id: raise APIValueError('id', 'id cannot be empty.') article = _get_article(i.id) if ctx.user.role_id == ROLE_AUTHORS and article.user_id != ctx.user.id: raise APIPermissionError('cannot delete article that belong to other') db.update('delete from articles where id=?', i.id) return True
def api_delete_wikipage(): i = ctx.request.input(id="") if not i.id: raise APIValueError("id", "bad parameter: id") page = _get_wikipage(i.id) if db.select_int("select count(id) from wiki_pages where wiki_id=? and parent_id=?", page.wiki_id, page.id) > 0: raise APIPermissionError("cannot delete non empty page.") db.update("delete from wiki_pages where id=?", page.id) return True
def create_app(): # from conf import dbconf # kwargs = dict([(s, getattr(dbconf, s)) for s in dir(dbconf) if s.startswith('DB_')]) # dbargs = kwargs.pop('DB_ARGS', {}) db.init(db_type = 'sqlite3', db_schema = 'weibo.db', db_host=False) if not os.path.isfile('weibo.db'): db.update('create table settings (id varchar(50) not null, value varchar(1000) not null, primary key(id))') db.update('create table users (id varchar(200) not null, name varchar(50) not null, image_url varchar(1000) not null, statuses_count bigint not null, friends_count bigint not null, followers_count bigint not null, verified bool not null, verified_type int not null, auth_token varchar(2000) not null, expired_time real not null, primary key(id))') return web.WSGIApplication(('urls',), document_root=os.path.dirname(os.path.abspath(__file__)), template_engine='jinja2', DEBUG=True)
def delete(self): ''' Delete row from database. ''' self.pre_delete and self.pre_delete() pk = self.__primary_key__.name #args = (getattr(self, pk), ) #db.update('delete from %s where %s=?' %(self.__table__, pk), *args) db.update('delete from %s where %s=?' % (self.__table__, pk), getattr(self, pk)) return self
def api_delete_category(): i = ctx.request.input(id='') if not i.id: raise APIValueError('id', 'id cannot be empty') cat = _get_category(i.id) if cat.locked: raise APIError('operation:failed', 'category', 'cannot delete category that is locked.') uncategorized = db.select_one('select id from categories where website_id=? and locked=?', ctx.website.id, True) db.update('delete from categories where id=?', i.id) db.update('update articles set category_id=?, version=version + 1 where category_id=?', uncategorized.id, i.id) return True
def api_delete_wiki(): " delete a wiki by id. " i = ctx.request.input(id="") if not i.id: raise APIValueError("id", "id cannot be empty.") wiki = _get_wiki(i.id) count = db.select_int("select count(id) from wiki_pages where wiki_id=?", wiki.id) if count > 0: raise APIValueError("id", "cannot delete non-empty wiki.") db.update("delete from wikis where id=?", wiki.id) return True
def api_delete_wikipage(): i = ctx.request.input(id='') if not i.id: raise APIValueError('id', 'bad parameter: id') page = _get_wikipage(i.id) if db.select_int( 'select count(id) from wiki_pages where wiki_id=? and parent_id=?', page.wiki_id, page.id) > 0: raise APIPermissionError('cannot delete non empty page.') db.update('delete from wiki_pages where id=?', page.id) return True
def update_resume(): _check_user() i = ctx.request.input(id='', title='') if not i.id: raise APIError('value', 'id', 'id is empty.') title = i.title.strip() if not title: raise APIError('value', 'title', 'title is empty') cv = get_default_cv(ctx.user.id) _check_user_id(cv.user_id) db.update('update resumes set title=?, version=version+1 where id=?', title, cv.id) return dict(result=True)
def api_delete_wiki(): ' delete a wiki by id. ' i = ctx.request.input(id='') if not i.id: raise APIValueError('id', 'id cannot be empty.') wiki = _get_wiki(i.id) count = db.select_int('select count(id) from wiki_pages where wiki_id=?', wiki.id) if count > 0: raise APIValueError('id', 'cannot delete non-empty wiki.') db.update('delete from wikis where id=?', wiki.id) return True
def update_section(): _check_user() i = ctx.request.input(id='', title='', description='') if not i.id: raise APIError('value', 'id', 'id is empty.') title = i.title.strip() description = i.description.strip() if not title: raise APIError('value', 'title', 'title is empty') section = db.select_one('select * from sections where id=?', i.id) _check_user_id(section.user_id) db.update('update sections set title=?, description=?, version=version+1 where id=?', title, description, section.id) db.update('update resumes set version=version+1 where id=?', section.resume_id) return dict(result=True)
def api_delete_category(): i = ctx.request.input(id='') if not i.id: raise APIValueError('id', 'id cannot be empty') cat = _get_category(i.id) if cat.locked: raise APIError('operation:failed', 'category', 'cannot delete category that is locked.') uncategorized = db.select_one( 'select id from categories where website_id=? and locked=?', ctx.website.id, True) db.update('delete from categories where id=?', i.id) db.update( 'update articles set category_id=?, version=version + 1 where category_id=?', uncategorized.id, i.id) return True
def update_section(): _check_user() i = ctx.request.input(id='', title='', description='') if not i.id: raise APIError('value', 'id', 'id is empty.') title = i.title.strip() description = i.description.strip() if not title: raise APIError('value', 'title', 'title is empty') section = db.select_one('select * from sections where id=?', i.id) _check_user_id(section.user_id) db.update( 'update sections set title=?, description=?, version=version+1 where id=?', title, description, section.id) db.update('update resumes set version=version+1 where id=?', section.resume_id) return dict(result=True)
def update(self): self.pre_updata and self.pre_updata() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.defualt setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update('updata `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self
def api_move_wikipages(): i = ctx.request.input(id='', index='') if not i.id: raise APIValueError('id', 'bad parameter id.') if not 'move_to' in i: raise APIValueError('move_to', 'bad parameter move_to.') if not i.index: raise APIValueError('index', 'bad parameter index.') try: index = int(i.index) except ValueError: raise APIValueError('index', 'bad parameter index.') # get the 2 pages: moving_page = _get_wikipage(i.id) wiki = _get_wiki(moving_page.wiki_id) parent_page = None # root if i.move_to: parent_page = _get_wikipage(i.move_to, wiki.id) # check to prevent recursive: pages = _get_wikipages(wiki, returnDict=True) if parent_page: p = parent_page while p.parent_id != '': if p.parent_id == moving_page.id: raise APIValueError('move_to', 'Will cause recursive.') p = pages[p.parent_id] # get current children: parent_id = parent_page.id if parent_page else '' L = [ p for p in pages.itervalues() if p.parent_id == parent_id and p.id != moving_page.id ] L.sort(cmp=lambda p1, p2: -1 if p1.display_order < p2.display_order else 1) # insert at index N: L.insert(index, moving_page) # update display order: with db.transaction(): n = 0 for p in L: db.update('update wiki_pages set display_order=? where id=?', n, p.id) n = n + 1 db.update('update wiki_pages set parent_id=? where id=?', parent_id, moving_page.id) return True
def api_wikis_pages_move(wpid, target_id): ''' Move wiki page from one node to another. ''' if not wpid: raise APIValueError('id', 'bad parameter id.') if not target_id: raise APIValueError('target_id', 'bad parameter target_id.') i = ctx.request.input() if not 'index' in i: raise APIValueError('index', 'bad parameter index.') try: index = int(i.index) except ValueError: raise APIValueError('index', 'bad parameter index.') # get the 2 pages: moving_page = _get_wikipage(wpid) wiki = _get_wiki(moving_page.wiki_id) parent_page = None if target_id=='ROOT': parent_page = None # root node else: parent_page = _get_wikipage(target_id, wiki._id) # check to prevent recursive: pages = _get_wikipages(wiki, returnDict=True) if parent_page: p = parent_page while p.parent_id != '': if p.parent_id==moving_page._id: raise APIValueError('target_id', 'Will cause recursive.') p = pages[p.parent_id] # get current children: parent_id = parent_page._id if parent_page else '' L = [p for p in pages.itervalues() if p.parent_id==parent_id and p._id != moving_page._id] L.sort(cmp=lambda p1, p2: cmp(p1.display_order, p2.display_order)) # insert at index N: L.insert(index, moving_page) # update display order: with db.transaction(): n = 0 for p in L: db.update('update wikipages set display_order=? where _id=?', n, p._id) n = n + 1 db.update('update wikipages set parent_id=? where _id=?', parent_id, moving_page._id) return dict(result=True)
def api_sort_categories(): ids = ctx.request.gets('id') cats = _get_categories() l = len(cats) if l != len(ids): raise APIValueError('id', 'bad id list.') sets = set([c.id for c in cats]) odict = dict() n = 0 for o in ids: if not o in sets: raise APIValueError('id', 'some id was invalid.') odict[o] = n n = n + 1 with db.transaction(): for c in cats: db.update('update categories set display_order=?, version=version + 1 where id=?', odict.get(c.id, l), c.id) return True
def auth_callback(): ''' Callback from sina, then redirect to previous url. ''' code = ctx.request.input(code='').code if not code: raise seeother('/s/auth_failed') client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK) r = client.request_access_token(code) access_token = r.access_token expires = r.expires_in uid = r.uid # get user info: client.set_access_token(access_token, expires) account = client.users.show.get(uid=uid) image = account.get(u'profile_image_url', u'about:blank') logging.info('got account: %s' % str(account)) name = account.get('screen_name', u'') or account.get('name', u'') id = u'weibo_%s' % uid user = auth.fn_load_user(id) if user: # update user if necessary: db.update('update user set name=?, oauth_image=?, oauth_access_token=?, oauth_expires=? where id=?', \ name, image, access_token, expires, id) else: db.insert('user', \ id = id, \ name = name, \ oauth_access_token = access_token, \ oauth_expires = expires, \ oauth_url = u'http://weibo.com/u/%s' % uid, \ oauth_image = image, \ admin = False) # make a signin cookie: cookie_str = auth.make_session_cookie(id, access_token, expires) logging.info('will set cookie: %s' % cookie_str) redirect = ctx.request.cookie(COOKIE_REDIRECT, '/') ctx.response.set_cookie(auth.COOKIE_AUTH, cookie_str, expires=expires) ctx.response.delete_cookie(COOKIE_REDIRECT) raise seeother(redirect)
def update(self): self.pre_update and self.pre_update() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default setattr(self, k, arg) L.append('`%s` = ?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update( 'update `%s` set %s where %s = ?' % (self.__table__, ','.join(L), pk), *args) return self
def _set_setting(website_id, kind, key, value): ''' Set setting by kind, key and value. ''' if len(kind) == 0 or len(kind) > 50 or len(key) == 0 or len(key) > 50: raise ValueError('invalid setting name.') if not isinstance(value, (str, unicode)): value = str(value) name = '%s:%s' % (kind, key) settings = dict( \ id = db.next_str(), \ website_id = website_id, \ kind = kind, \ name = name, \ value = value, \ creation_time = time.time(), \ version = 0) db.update('delete from settings where name=? and website_id=?', name, website_id) db.insert('settings', **settings)
def api_sort_categories(): ids = ctx.request.gets('id') cats = _get_categories() l = len(cats) if l != len(ids): raise APIValueError('id', 'bad id list.') sets = set([c.id for c in cats]) odict = dict() n = 0 for o in ids: if not o in sets: raise APIValueError('id', 'some id was invalid.') odict[o] = n n = n + 1 with db.transaction(): for c in cats: db.update( 'update categories set display_order=?, version=version + 1 where id=?', odict.get(c.id, l), c.id) return True
def auth_callback_weibo(): provider = 'SinaWeibo' p = sns.create_client(provider) callback = 'http://%s/manage/setting/auth_callback_weibo' % ctx.request.host i = ctx.request.input(code='', state='') code = i.code if not code: raise IOError('missing code') state = i.state r = p.request_access_token(code, callback) thirdpart_id = r['uid'] info = p.users.show.get(uid=thirdpart_id) name = info['screen_name'] auth_id = '%s-%s' % (provider, thirdpart_id) auth_token = r['access_token'] expires_time = r['expires'] db.update('delete from snstokens where auth_provider=?', provider) SNSTokens(auth_id=auth_id, auth_provider=provider, auth_name=name, auth_token=auth_token, expires_time=expires_time).insert() raise seeother('/manage/setting/snstokens')
def update(self): ''' Update class's property to database. ''' self.pre_update and self.pre_update() L = [] args = [] for k, v in self.__mappings__.iteritems(): if v.updatable: if hasattr(self, k): arg = getattr(self, k) else: arg = v.default() setattr(self, k, arg) L.append('`%s`=?' % k) args.append(arg) pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self
def set_text(kind, key, value): ''' Set text by kind, key and value. ''' if len(kind) == 0 or len(kind) > 50 or len(key) == 0 or len(key) > 50: raise ValueError('invalid setting name.') if not isinstance(value, (str, unicode)): value = str(value) name = '%s:%s' % (kind, key) text = dict( \ id = db.next_str(), \ website_id = ctx.website.id, \ kind = kind, \ name = name, \ value = value, \ creation_time = time.time(), \ version = 0) db.update('delete from texts where name=? and website_id=?', name, ctx.website.id) db.insert('texts', **text) cache.client.delete('TEXT:%s:%s:%s' % (ctx.website.id, kind, key))
def set_text(name, value): ''' Set text by name and value. ''' pos = name.find('_') if pos<=0: raise ValueError('bad setting name: %s must be xxx_xxx' % name) kind = name[:pos] current = time.time() if 0==db.update('update texts set value=?, modified_time=?, version=version+1 where name=?', value, current, name): st = dict(id=db.next_str(), kind=kind, name=name, value=value, creation_time=current, modified_time=current, version=0) db.insert('texts', **st)
def api_move_wikipages(): i = ctx.request.input(id="", index="") if not i.id: raise APIValueError("id", "bad parameter id.") if not "move_to" in i: raise APIValueError("move_to", "bad parameter move_to.") if not i.index: raise APIValueError("index", "bad parameter index.") try: index = int(i.index) except ValueError: raise APIValueError("index", "bad parameter index.") # get the 2 pages: moving_page = _get_wikipage(i.id) wiki = _get_wiki(moving_page.wiki_id) parent_page = None # root if i.move_to: parent_page = _get_wikipage(i.move_to, wiki.id) # check to prevent recursive: pages = _get_wikipages(wiki, returnDict=True) if parent_page: p = parent_page while p.parent_id != "": if p.parent_id == moving_page.id: raise APIValueError("move_to", "Will cause recursive.") p = pages[p.parent_id] # get current children: parent_id = parent_page.id if parent_page else "" L = [p for p in pages.itervalues() if p.parent_id == parent_id and p.id != moving_page.id] L.sort(cmp=lambda p1, p2: -1 if p1.display_order < p2.display_order else 1) # insert at index N: L.insert(index, moving_page) # update display order: with db.transaction(): n = 0 for p in L: db.update("update wiki_pages set display_order=? where id=?", n, p.id) n = n + 1 db.update("update wiki_pages set parent_id=? where id=?", parent_id, moving_page.id) return True
def api_sort_navigations(): ''' Sort navigations. ''' ids = ctx.request.gets('_id') navs = _get_navigations() l = len(navs) if l != len(ids): raise APIValueError('_id', 'bad id list.') sets = set([n._id for n in navs]) odict = dict() n = 0 for o in ids: if not o in sets: raise APIValueError('_id', 'some id was invalid.') odict[o] = n n = n + 1 with db.transaction(): for n in navs: db.update('update navigations set display_order=?, version=version+1 where _id=?', odict.get(n._id, l), n._id) _clear_navigations_cache() return dict(result=True)
def generate_tables(): if not db.engine: db.create_engine('awesome.db') sql = lambda x:''.join(x().__sql__.split('\n')[1:]) db.update(sql(User)) db.update(sql(Blog)) db.update(sql(Comment))
def generate_tables(): if not db.engine: db.create_engine('awesome.db') sql = lambda x: ''.join(x().__sql__.split('\n')[1:]) db.update(sql(User)) db.update(sql(Blog)) db.update(sql(Comment))
def delete_section(): _check_user() i = ctx.request.input(id='') if not i.id: raise APIError('value', 'id', 'id is empty.') section = db.select_one('select * from sections where id=?', i.id) _check_user_id(section.user_id) cv = get_default_cv(ctx.user.id) sections = db.select('select * from sections where resume_id=? order by display_order', cv.id) display_ids = [s.id for s in sections if s.id != i.id] db.update('delete from entries where section_id=?', i.id) db.update('delete from sections where id=?', i.id) n = 0 for i in display_ids: db.update('update sections set display_order=? where id=?', n, i) db.update('update resumes set version=version+1 where id=?', cv.id) return dict(result=True)
def api_sort_navigations(): ''' Sort navigations. ''' ids = ctx.request.gets('_id') navs = _get_navigations() l = len(navs) if l != len(ids): raise APIValueError('_id', 'bad id list.') sets = set([n._id for n in navs]) odict = dict() n = 0 for o in ids: if not o in sets: raise APIValueError('_id', 'some id was invalid.') odict[o] = n n = n + 1 with db.transaction(): for n in navs: db.update( 'update navigations set display_order=?, version=version+1 where _id=?', odict.get(n._id, l), n._id) _clear_navigations_cache() return dict(result=True)
def do_admin(): global _APP_ID, _APP_SECRET, _ADMIN_PASS i = ctx.request.input() if i.passwd != _ADMIN_PASS: raise forbidden() admin_pass = i.get("new_passwd", "") app_id = i.get("app_id", "") app_secret = i.get("app_secret", "") msg = "" if admin_pass and app_id and app_secret: db.update("delete from settings") db.update("insert into settings (id, value) values (?, ?)", "app_id", app_id) db.update("insert into settings (id, value) values (?, ?)", "app_secret", app_secret) db.update("insert into settings (id, value) values (?, ?)", "admin_pass", admin_pass) msg = "Updated!" _APP_ID = app_id _APP_SECRET = app_secret _ADMIN_PASS = admin_pass return """<html> <body> <p>%s</p> <form action="/admin" method="post"> <p>App ID:</p> <p><input type="text" name="app_id" value="%s" /></p> <p>App Secret:</p> <p><input type="text" name="app_secret" value="%s" /></p> <p>Old Password:</p> <p><input type="text" name="passwd" readonly="readonly" value="%s" /></p> <p>New Password:</p> <p><input type="text" name="new_passwd" value="%s" /></p> <p>WARNING: click submit will update app_id, app_secret and admin password!</p> <p><input type="submit" name="submit" value="Submit" /></p> </form> </body> </html> """ % ( msg, _APP_ID, _APP_SECRET, _ADMIN_PASS, _ADMIN_PASS, )
def main(): if raw_input('To install iTranswarp, type Y and press ENTER: ') != 'Y': print 'Install cancelled.' exit(1) print 'Prepare to install iTranswarp...' try: print 'Checking Python version...', _check_version() print 'Checking Python Imaging Library...', _check_pil() print 'Checking Redis...', _check_redis() host = raw_input('Database host (localhost): ') port = raw_input('Database port (3306): ') user = raw_input('Database user (root): ') dbpass = raw_input('Database password: '******'': port = '3306' db.init(db_type='mysql', db_schema='itrans', \ db_host=host or 'localhost', db_port=int(port), \ db_user=user or 'root', db_password=dbpass, \ use_unicode=True, charset='utf8') print 'Creating tables . . .', for sql in CREATE_TABLES: if not sql.startswith('--'): db.update(sql) print '.', print '\nInit database ok.' email = raw_input('Super admin email: ').strip().lower() passwd = raw_input('Super admin password: '******'iTranswarp', 'localhost') if db.select_int('select count(*) from mysql.user where user=?', 'www-data') == 0: db.update( 'create user \'www-data\'@\'localhost\' identified by \'www-data\'' ) db.update( 'grant select,insert,update,delete on itrans.* to \'www-data\'@\'localhost\' identified by \'www-data\'' ) db.update('update users set role_id=0, passwd=? where email=?', passwd, email) print 'Install successfully!' except Exception, e: print 'Install failed:', e.message raise
def delete_section(): _check_user() i = ctx.request.input(id='') if not i.id: raise APIError('value', 'id', 'id is empty.') section = db.select_one('select * from sections where id=?', i.id) _check_user_id(section.user_id) cv = get_default_cv(ctx.user.id) sections = db.select( 'select * from sections where resume_id=? order by display_order', cv.id) display_ids = [s.id for s in sections if s.id != i.id] db.update('delete from entries where section_id=?', i.id) db.update('delete from sections where id=?', i.id) n = 0 for i in display_ids: db.update('update sections set display_order=? where id=?', n, i) db.update('update resumes set version=version+1 where id=?', cv.id) return dict(result=True)
def do_admin(): global _APP_ID, _APP_SECRET, _ADMIN_PASS i = ctx.request.input() if i.passwd != _ADMIN_PASS: raise forbidden() admin_pass = i.get('new_passwd', '') app_id = i.get('app_id', '') app_secret = i.get('app_secret', '') msg = '' if admin_pass and app_id and app_secret: db.update('delete from settings') db.update('insert into settings (id, value) values (?, ?)', 'app_id', app_id) db.update('insert into settings (id, value) values (?, ?)', 'app_secret', app_secret) db.update('insert into settings (id, value) values (?, ?)', 'admin_pass', admin_pass) msg = 'Updated!' _APP_ID = app_id _APP_SECRET = app_secret _ADMIN_PASS = admin_pass return '''<html> <body> <p>%s</p> <form action="/admin" method="post"> <p>App ID:</p> <p><input type="text" name="app_id" value="%s" /></p> <p>App Secret:</p> <p><input type="text" name="app_secret" value="%s" /></p> <p>Old Password:</p> <p><input type="text" name="passwd" readonly="readonly" value="%s" /></p> <p>New Password:</p> <p><input type="text" name="new_passwd" value="%s" /></p> <p>WARNING: click submit will update app_id, app_secret and admin password!</p> <p><input type="submit" name="submit" value="Submit" /></p> </form> </body> </html> ''' % (msg, _APP_ID, _APP_SECRET, _ADMIN_PASS, _ADMIN_PASS)
def delete_entry(): _check_user() i = ctx.request.input(id='') if not i.id: raise APIError('value', 'id', 'id is empty.') entry = db.select_one('select * from entries where id=?', i.id) _check_user_id(entry.user_id) entries = db.select('select * from entries where section_id=? order by display_order', entry.section_id) display_ids = [en.id for en in entries if en.id != i.id] db.update('delete from entries where id=?', i.id) n = 0 for i in display_ids: db.update('update entries set display_order=? where id=?', n, i) db.update('update sections set version=version+1 where id=?', entry.section_id) return dict(result=True)
def main(): if raw_input('To install iTranswarp, type Y and press ENTER: ')!='Y': print 'Install cancelled.' exit(1) print 'Prepare to install iTranswarp...' try: print 'Checking Python version...', _check_version() print 'Checking Python Imaging Library...', _check_pil() print 'Checking Redis...', _check_redis() host = raw_input('Database host (localhost): ') port = raw_input('Database port (3306): ') user = raw_input('Database user (root): ') dbpass = raw_input('Database password: '******'': port = '3306' db.init(db_type='mysql', db_schema='itrans', \ db_host=host or 'localhost', db_port=int(port), \ db_user=user or 'root', db_password=dbpass, \ use_unicode=True, charset='utf8') print 'Creating tables . . .', for sql in CREATE_TABLES: if not sql.startswith('--'): db.update(sql) print '.', print '\nInit database ok.' email = raw_input('Super admin email: ').strip().lower() passwd = raw_input('Super admin password: '******'iTranswarp', 'localhost') if db.select_int('select count(*) from mysql.user where user=?', 'www-data')==0: db.update('create user \'www-data\'@\'localhost\' identified by \'www-data\'') db.update('grant select,insert,update,delete on itrans.* to \'www-data\'@\'localhost\' identified by \'www-data\'') db.update('update users set role_id=0, passwd=? where email=?', passwd, email) print 'Install successfully!' except Exception, e: print 'Install failed:', e.message raise
def delete_entry(): _check_user() i = ctx.request.input(id='') if not i.id: raise APIError('value', 'id', 'id is empty.') entry = db.select_one('select * from entries where id=?', i.id) _check_user_id(entry.user_id) entries = db.select( 'select * from entries where section_id=? order by display_order', entry.section_id) display_ids = [en.id for en in entries if en.id != i.id] db.update('delete from entries where id=?', i.id) n = 0 for i in display_ids: db.update('update entries set display_order=? where id=?', n, i) db.update('update sections set version=version+1 where id=?', entry.section_id) return dict(result=True)
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'learned by xiaojian' from models import User, Blog, Comment import time, logging from transwarp import db logging.basicConfig(level=logging.INFO) db.create_engine(user='******', password='******',database='test') u = User(name='Test', email = '*****@*****.**', password='******',image='about:blank') db.update(' %s ' % u.__sql__() ) print User.__table__ u.insert() print 'new user id:',u.id u1 = User.find_first('where email=?', '*****@*****.**') print 'find ',u1.name #u1.delete() u2 = User.find_first('where email=?', '*****@*****.**') print 'find :',u2
def _delete_settings(website_id, kind): db.update('delete from settings where kind=? and website_id=?', kind, website_id)
def delete_resources(ref_id): db.update('update resources set deleted=? where ref_id=?', True, ref_id)
def delete_settings(kind): db.update('delete from settings where kind=?', kind)
# {"id":2,"name":"Bob"} # ] # 如果要执行 insert update deletecaozuo ,执行 update() 方法,返回受影响的行数 # n=db.update('update users set name = "Lily" where id in (?,?',4,5) # update() 函数签名为 update(slq,*args) # 统一用?作为占位符,并传入可变参数来绑定,从根本上避免 SQL 注入共计 # 每个 select() 和 update() 调用,都隐含地自动打开并关闭了数据库连接,这样上层调用者完全不必关心数据库地层连接 # 但是,如果要在一个数据库连接里执行多个 SQL 语句怎么办?我们用一个 with 语句实现: with db.connection(): db.select('...') db.select('...') db.select('...') # 如果要在一个数据库失误中执行多个SQL 语句怎么办?我们还是用一个 with 语句实现: with db.transaction(): db.select('...') db.update('...') db.insert('...') #实现 DB 模块 #由于模块是全局对象,模块变量是全局唯一变量,有两个重要的变量: #代码在 operational_training 中编写 # -*- coding: UTF-8 -*- import threading # 数据库引擎对象 class _Engine(object): def __init__(self, connect): self._connect = connect def connect(self): return self._connect()
def _delete_setting(website_id, kind, key): name = '%s:%s' % (kind, key) db.update('delete from settings where name=? and website_id=?', name, website_id)
pk = self.__primary_key__.name args.append(getattr(self, pk)) db.update('update `%s` set %s where %s=?' % (self.__table__, ','.join(L), pk), *args) return self def delete(self): self.pre_delete and self.pre_delete() pk = self.__primary_key__.name args = (getattr(self, pk), ) db.update('delete from `%s` where `%s`=?' % (self.__table__, pk), *args) return self def insert(self): self.pre_insert and self.pre_insert() params = {} for k, v in self.__mappings__.iteritems(): if v.insertable: if not hasattr(self, k): setattr(self, k, v.default) params[v.name] = getattr(self, k) db.insert('%s' % self.__table__, **params) return self if __name__=='__main__': logging.basicConfig(level=logging.DEBUG) db.create_engine('www-data', 'www-data', 'test') db.update('drop table if exists user') db.update('create table user (id int primary key, name text, email text, passwd text, last_modified real)') import doctest doctest.testmod()
#!/usr/bin/env python # coding=utf-8 #db.py from transwarp import db db.create_engine(user='******',password='******',database='littlesnail',host='127.0.0.1',port=3306) users = db.select('select * from user') n = db.update('insert into user(id,name) values(?,?)',4,'Jack') with db.connection(): db.select('...') db.update('...') db.update('...') #数据库引擎对象: class _Engine(object): def __init__(self,connect): self.connect = connect def connect(self): return self.connect() engine = None #持有数据库连接的上下文对象: class _DbCtx(threading.local): def __init__(self): self.connection = None self.transactions = 0 def is_init(self): return not self.connection is None def init(self): self.connection = LasyConnection() self.transactions = 0 def cleanup(self): self.connection,cleanup()