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 create_website(email, name, domain): # generate password: L = [] for i in range(10): n = int(random.random() * 62) if n < 10: L.append(chr(n + 48)) elif n < 36: L.append(chr(n + 55)) else: L.append(chr(n + 61)) passwd = ''.join(L) md5passwd = hashlib.md5(passwd).hexdigest() current = time.time() website = dict( id=db.next_str(), disabled=False, domain=domain, name=name, creation_time=current, modified_time=current, version=0) with db.transaction(): db.insert('websites', **website) create_user(website['id'], email, md5passwd, name, ROLE_ADMINISTRATORS, locked=True) return passwd
def _store_files(kind, name, files): ''' Store a group of files as attachment. Args: kind: attachment type. e.g. 'image/cover' name: attachment name. files: list of (mime, meta, data). Returns: Attachments object. ''' ref_id = db.next_id() atta = Attachments(_id=ref_id, user_id=ctx.user._id, kind=kind, name=name) resources = [] for mime, meta, data in files: r_id = db.next_id() url = '/files/%s/%s' % (datetime.now().strftime('%Y/%m/%d'), r_id) r = Resources(_id=r_id, ref_id=ref_id, url=url, size=len(data), mime=mime, meta=meta, data=data) resources.append(r) atta.size = resources[0].size atta.resource_ids = ','.join([r._id for r in resources]) with db.transaction(): atta.insert() for r in resources: r.insert() return atta
def update_data(): if request.method == 'GET': return '<html><h1>404!!你访问的页面不存在</h1><body></body></html>' if not session.get('username'): return redirect(url_for('admin_login')) t_name = request.form['table'] op = request.form['operation'] data = request.form.getlist('data[]') num = len(data) if t_name == 'department': with db.transaction(): i = 1 if num % 2 else 0 while i < num: departmentID = data[i] departmentName = data[i+1] i += 2 departmentE = departments.find_first( 'where departmentID=? or departmentName=?', departmentID, departmentName) if op == 'add': if departmentE: return "error! The id have already exists" department = departments( departmentID=departmentID, departmentName=departmentName) lg = log( details=u'{} add {} {} into table department' .format(session.get('username'), departmentID, departmentName)) try: department.insert() lg.insert() except Exception, e: return e.message elif op == 'delete': if not departmentE: return "error! the item doesn't exist" lg = log( details=u'{} delete {} {} from table department' .format(session.get('username'), departmentID, departmentName)) try: departmentE.delete() lg.insert() except Exception, e: return e
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_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_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 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 parse_dev(self, table_index, dev_id, dev_type, data_content): table_index = int(table_index) if Data.count_all(sub_name = str(table_index)) > MAX_TABLE_LINES: table_index+=1 cdtm = Data_Table_Map.find_first("where `index` = ?", table_index) if cdtm == None: Data_Table_Map.add_table(table_index) with transaction() as tr: for dev_info in self._data_infos: if dev_info['dev_type'] == dev_type.strip(): for index in range(len(dev_info['data_content'])): pos = (dev_info['data_content'][index]['start_pos']-1)/2 d = Data(device_id = dev_id, type_id = dev_info['data_content'][index]['type_id'], owner=dev_info['data_content'][index]['owner'], value = data_content[pos]) d.insert(sub_name=str(table_index)) cdtm = Data_Table_Map.find_first("where `index` = ?", table_index) cdtm.end_time = time.time() cdtm.update()
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 parse_dev(self, table_index, dev_id, dev_type, data_content): table_index = int(table_index) if Data.count_all(sub_name=str(table_index)) > MAX_TABLE_LINES: table_index += 1 cdtm = Data_Table_Map.find_first("where `index` = ?", table_index) if cdtm == None: Data_Table_Map.add_table(table_index) with transaction() as tr: for dev_info in self._data_infos: if dev_info['dev_type'] == dev_type.strip(): for index in range(len(dev_info['data_content'])): pos = (dev_info['data_content'][index]['start_pos'] - 1) / 2 d = Data( device_id=dev_id, type_id=dev_info['data_content'][index]['type_id'], owner=dev_info['data_content'][index]['owner'], value=data_content[pos]) d.insert(sub_name=str(table_index)) cdtm = Data_Table_Map.find_first("where `index` = ?", table_index) cdtm.end_time = time.time() cdtm.update()
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)
# [ # {"id":1,"name":"Jack"}, # {"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 auth_callback_weibo(): provider = 'SinaWeibo' p = sns.create_client(provider) redirect = _get_redirect(excludes='/auth/') callback = 'http://%s/auth/callback/%s' % (ctx.request.host, provider) 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'] auth_id = '%s-%s' % (provider, thirdpart_id) auth_token = r['access_token'] expires = r['expires'] user = None auser = AuthUsers.select_one('where auth_id=?', auth_id) if auser: # already signed in before: auser.auth_token = auth_token auser.expires = expires auser.update() user = Users.get_by_id(auser.user_id) make_session_cookie(provider, auser._id, auth_token, expires) else: # not signed in before, so try to get info: info = p.users.show.get(uid=thirdpart_id) user_id = db.next_id() email = info['email'] if 'email' in info else '%s@tmp' % user_id name = info['screen_name'] image_url = info['profile_image_url'] user = Users(_id=user_id, role=ROLE_GUEST, binds=provider, email=email, name=name, image_url=image_url, passwd='') auser = AuthUsers( \ user_id = user_id, \ auth_id = auth_id, \ auth_provider = provider, \ auth_token = auth_token, \ expires_time = expires \ ) with db.transaction(): user.insert() auser.insert() make_session_cookie(provider, auser._id, auth_token, expires) jscallback = ctx.request.get('jscallback', '') if jscallback: ctx.response.write( r'''<html><body><script> window.opener.%s({'id': '%s', 'name': '%s', 'image_url': '%s'}); self.close(); </script></body></html>''' % (jscallback, user._id, user.name.replace('\'', '\\\'').replace( '\n', '').replace('\r', ''), user.image_url)) return raise seeother('/')