async def test_query(self): uri = self.url + '/query' student_2 = await self.db.createObject('users', username='******', password='******', secret='12423') response = await self.post_request_return_object(uri, id=self.user_st['id']) self.assertEqual(1, response['code']) # student await self.login_object(self.user_st) response = await self.post_request_return_object(uri, id=student_2['id']) print_debug('test_query:', response) self.assertEqual(0, len(response)) # student query ta response = await self.post_request_return_object(uri, id=self.user_ta['id']) self.assertIsInstance(response, list) private_keys = ['student_courses', 'ta_courses'] nonavalibal_keys = [ 'validate_time', 'validate_code', 'secret', 'password' ] for res in response: print_debug('test-query: ', res) for keyword in private_keys + nonavalibal_keys: self.assertNotIn(keyword, res.keys()) self.assertListEqual([res['id'], res['username'], res['email']], [ self.user_ta['id'], self.user_ta['username'], self.user_ta['email'] ]) # student query st response = await self.post_request_return_object(uri, id=student_2['id']) self.assertIsInstance(response, list) self.assertEqual(0, len(response)) # student query self response = await self.post_request_return_object(uri, id=self.user_st['id']) self.assertIsInstance(response, list) for res in response: # print_debug('test') for keyword in nonavalibal_keys: self.assertNotIn(keyword, res.keys()) #ta querys await self.login_object(self.user_ta) response = await self.post_request_return_object(uri, id=self.user_st['id']) self.assertIsInstance(response, list) self.assertEqual(1, len(response)) for keyword in nonavalibal_keys: self.assertNotIn(keyword, response[0].keys())
async def get_response(self, url, *args, **kw): header = tornado.httputil.HTTPHeaders({'content-type': 'application/json', 'Cookie': self.user_id_cookie}) print_debug('''si-client fetch {url} with header = {header}'''.format(url = url, header = header)) res = await self.client.fetch(url, headers = header, *args, **kw) for cookie in res.headers.get_list('Set-Cookie'): parsed_cookie = tornado.httputil.parse_cookie(cookie) if 'user_id' in parsed_cookie.keys(): self.user_id_cookie = '''user_id=\"{secure_cookie}\"'''.format(secure_cookie = parsed_cookie['user_id']) return res
async def deleteObject(self, **kw): si_table_name = self.table_name plst = [] valuelist = [] for key, value in kw.items(): plst.append(str(key) + ' = %s') valuelist.append(value) slst = ' AND '.join(plst) print_debug("slst = ", slst) return await self.db.execute( '''DELETE FROM {table_name} WHERE {conditions}'''.format( table_name=si_table_name, conditions=slst), *valuelist)
async def queryone(self, stmt, *args): """Query for exactly one result. Raises NoResultError if there are no results, or ValueError if there are more than one. """ results = await self.query(stmt, *args) if len(results) == 0: raise NoResultError() elif len(results) > 1: raise ValueError("Expected 1 result, got %d" % len(results)) print_debug(results[0]) return results[0]
async def getObject(self, cur_user=None, **kw): si_table_name = self.table_name # print_debug('getobject: ', kw) kw = self.filterKeys(kw) # print_debug('getobject after filter: ', kw) plst = [] valuelist = [] for key, value in kw.items(): plst.append(str(key) + ' = %s') valuelist.append(value) slst = ' AND '.join(plst) print_debug("slst = ", slst) res = await self.db.query( '''SELECT * FROM {table_name} WHERE {conditions}'''.format( table_name=si_table_name, conditions=slst), *valuelist) return res
async def querylr(self, l, r, **kw): si_table_name = self.table_name plst = [] valuelist = [] kw = self.filterKeys(kw) for key, value in kw.items(): plst.append(str(key) + ' = %s') valuelist.append(value) if (plst): slst = 'WHERE ' + ' AND '.join(plst) else: slst = '' print_debug("slst = ", slst) # slst = '' stmt = 'SELECT * FROM {table_name} {conditions} LIMIT {n} OFFSET {s}'.format( n=r - l + 1, s=l - 1, table_name=si_table_name, conditions=slst) print_debug('querylr: ', stmt, *valuelist) res = await self.db.query(stmt, *valuelist) for x in res: for key, value in x.items(): # print_debug(key, isinstance(value, datetime.datetime)) if (isinstance(value, datetime.datetime)): x[key] = int(time.mktime(value.timetuple())) print_debug(res) rtn = {} rtn['count'] = (await self.db.query( 'SELECT COUNT(*) FROM {table_name} {conditions}'.format( table_name=si_table_name, conditions=slst), *valuelist))[0]['count'] rtn['list'] = res return rtn
async def login_object(self, obj, client = None): print_debug('login_object: ', obj, client)
async def post_request(self, uri, client = None, **kw): print_debug('post_request', kw) return await self.get_response(uri, method = 'POST', body = json.dumps(kw).encode(), client = client)
async def execute_without_args(self, stmt): print_debug('exe-without: ', stmt) with (await self.db.cursor()) as cur: await cur.execute(stmt)
async def release_lock(self, hash_id): self.lock[hash_id % self.lockN].release() print_debug('release lock lock')
async def acquire_lock(self, hash_id): await self.lock[hash_id % self.lockN].acquire() print_debug('before_ac lock')