def _insert(self, values, return_id=False, raw_values=False): query = sql.InsertQuery(self.model, getConnection(self.banco)) query.insert_values(values, raw_values) ret = query.execute_sql(return_id) #O commit automatico so eh valido para a conexao padrao do banco query.connection._commit() return ret
def test_update_contact(self): nickname = 'contact-name-1-bis' thumbnail = 'xxx-bis' id = '1000' payload = { 'contact': { 'id': id, 'nickname': nickname, 'thumbnail': thumbnail } } userId = 'user1' mock_event = make_mock_event(userId, payload) result = handler.post_contact(mock_event, None) assert result is True schema = os.environ['PGSCHEMA'] connection = getConnection() with closing(connection): with closing(connection.cursor( cursor_factory=NamedTupleCursor)) as cursor: cursor.execute( f'SELECT * FROM "{schema}"."contact" WHERE id=%s', (id, )) assert cursor.rowcount == 1 for record in cursor: assert record.id == id assert record.nickname == nickname assert record.thumbnail == thumbnail assert record.user_id == userId
def test_handle_successful_borrower_validation(self, mock_send_message): mock_message = make_mock_message( { 'operation': IncomingOperations.VALIDATE_BOOK_BORROWER.value, 'userId': 'user5', 'contactId': '1005', 'lendingId': '1', 'bookId': '2000' }, 'mock-reply-address') handler.handle_messages(event=mock_message, context=None) # Assert the send_message method is called once, with correct parameters mock_send_message.assert_called_once_with( { 'operation': OutgoingOperations.VALIDATE_BOOK_BORROWER.value, 'userId': 'user5', 'lendingId': '1', 'bookId': '2000', 'result': { 'status': BorrowingStatus.BORROWER_VALIDATED.value, 'contact': 'contact-1005' } }, 'mock-reply-address') # Assert the borrowing is saved accodingly in database schema = os.environ['PGSCHEMA'] connection = getConnection() with closing(connection): with closing(connection.cursor( cursor_factory=NamedTupleCursor)) as cursor: cursor.execute( f'SELECT * FROM "{schema}"."borrowing" WHERE user_id=%s AND lending_id=%s AND contact_id=%s AND book_id=%s', ('user5', '1', '1005', '2000')) assert cursor.rowcount == 1
def post(self): req = json_decode(self.request.body) user_id = req["user_id"] try: with getConnection() as conn: data = conn.execute( 'SELECT face_vec FROM userlist WHERE user_id=%s', (user_id, )) vec_mine = data.fetchone() data = conn.execute( 'SELECT user_id, face_vec FROM userlist WHERE user_id!=%s', (user_id, )) user_list = data.fetchall() sim_list = [] for user in user_list: sim = cosSimilarity(vec_mine[0], user[1]) if sim > 0.4: sim_list.append([sim, user[0]]) new_sim_list = sorted(sim_list, reverse=True) data = {"user_id": user_id, "list": [x[1] for x in new_sim_list]} except: data = {"result": "0"} self.write(json.dumps(data))
def start(self, personId, localTaskId): taskObject = task.Task() taskItem = json.loads(utils.getConnection(taskObject.details(localTaskId))) taskId = taskItem['task'][0]['id'] time = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S") infos = {'personid':personId, 'starttime':time, 'taskid':taskId} jsonObject = utils.postConnection('timer/', infos) urlString = self.current(personId) return urlString
def pause(self, personId): # calculate the amount of time lapsed between the starttime and now, and sum that value with the value in the time field (i.e. time = time + (now - starttime)). Then nullify the starttime field. taskObject = task.Task() taskLocalId = json.loads(utils.getConnection(self.current(personId))) timer = taskLocalId['timer'][0] startTime = timer['starttime'] timer['starttime'] = None total = float(timer['time']) + (datetime.datetime.utcnow() - startTime) timer['time'] = total return None
def __setstate__(self, obj_dict): """Unpickling support.""" # Rebuild list of field instances obj_dict['select_fields'] = [ name is not None and obj_dict['model']._meta.get_field(name) or None for name in obj_dict['select_fields'] ] self.__dict__.update(obj_dict) # XXX: Need a better solution for this when multi-db stuff is # supported. It's the only class-reference to the module-level # connection variable. self.connection = getConnection(self.banco)
def test_delete_contact(self): userId = 'user3' id = '1003' mock_event = make_mock_event(userId, {'id': id}) result = handler.delete_contact(mock_event, None) assert result is True schema = os.environ['PGSCHEMA'] connection = getConnection() with closing(connection): with closing(connection.cursor( cursor_factory=NamedTupleCursor)) as cursor: cursor.execute( f'SELECT * FROM "{schema}"."contact" WHERE id=%s', (id, )) assert cursor.rowcount == 0
def post(self): req = json_decode(self.request.body) img_path = req["image_path"] user_id = req["user_id"] img = io.BytesIO(urllib.request.urlopen(img_path).read()) img = Image.open(img).convert('RGB') try: vector = getVec(img, mtcnn, resnet) except: self.write(json.dumps({"result": "-1"})) return try: with getConnection() as conn: conn.execute( 'INSERT INTO userlist (user_id, face_vec) VALUES (%s, %s)', (user_id, list(vector.astype(float)))) data = {"result": "1"} except: data = {"result": "0"} self.write(json.dumps(data))
def test_handle_returned_book(self): # user does not exists mock_message = make_mock_message({ 'operation': IncomingOperations.RETURN_LENT_BOOK.value, 'userId': 'user6', 'contactId': '1006', 'lendingId': '2', 'bookId': 'book-id-2' }) handler.handle_messages(event=mock_message, context=None) schema = os.environ['PGSCHEMA'] connection = getConnection() with closing(connection): with closing(connection.cursor( cursor_factory=NamedTupleCursor)) as cursor: cursor.execute( f'SELECT * FROM "{schema}"."borrowing" WHERE user_id=%s AND lending_id=%s AND contact_id=%s AND book_id=%s', ('user6', '2', '1006', 'book-id-2')) assert cursor.rowcount == 0
def __init__(self, model, banco): self.banco = banco self.model = model self.connection = getConnection(self.banco) super(MultiBdQueryBase, self).__init__( self.model, self.connection, WhereNode)
import pandas as pd import cx_Oracle as oracle import utils import matplotlib.pyplot as plt from io import StringIO conn = utils.getConnection() cur = conn.cursor() cur.execute('SELECT LON,LAT,AVG(SPEED_GPS) FROM TR_GPSTRACK_0700_0710 GROUP BY LON,LAT') rows = cur.fetchall() cur.executemany('INSERT INTO TR_GPSTRACK_0700_0710_AVGSPEED(LON,LAT,SPEED_GPS_AVG) VALUES(:1,:2,:3)',rows) conn.commit() cur.execute('SELECT * FROM TR_GPSTRACK_0700_0710_AVGSPEED') data = utils.formatall(cur) data.to_csv('avg_speed.csv') # cm = plt.cm.get_cmap('RdYlBu') # sc = plt.scatter(data.LON,data.LAT,c=data.SPEED_GPS_AVG,vmin=0,vmax=120,s=2,cmap=cm) # plt.colorbar(sc) # plt.show() cur.close() conn.close()