Ejemplo n.º 1
0
 def GET(self):
     cookie = web.cookies()
     web.setcookie('user', '', 3600)
     web.setcookie('color', '', 3600)
     db.delete('user', where='user="******"'.format(cookie.user))
     db.delete('data', where='user="******"'.format(cookie.user))
     return render.bye()
Ejemplo n.º 2
0
def process_block(height: int, blockhash: str):

    print('processing block: height=%d hash=%s' % (height, blockhash))

    height_bin = b'HGHT' + struct.pack('>I', height)
    blockhash_bin = binascii.unhexlify(blockhash)
    h = db.get(height_bin)

    if h is not None and h == blockhash_bin and db.get(b'HASH' +
                                                       blockhash_bin):
        # block already seen and processed
        print('* already seen and processed')
        return

    if h is not None and h != blockhash_bin:
        # seen another block with this height, delete old info
        print('* reorg')
        db.delete(b'HASH' + h)

    else:
        # this is new block
        print('* new block')

    db.put(height_bin, binascii.unhexlify(blockhash))

    process_transactions(blockhash)
Ejemplo n.º 3
0
def merge(phone_id, card_id):
    """手机临时账号和校园卡账号合并"""
    record_table = 'record'
    t = db.transaction()
    phone_id, card_id = int(phone_id), int(card_id)
    # db.update(record_table, where="lost_id=%i" % phone_id, lost_id=card_id)
    # db.update(record_table, where="find_id=%i" % phone_id, find_id=card_id)
    # # 删除合并用户
    # phone_user = db.select(_table, where="id=%i" % phone_id, limit=1, what='phone')
    # try:
    #     db.delete(_table, where="id=%i" % phone_id)
    # except:
    #     db.update(_table, where="id=%i" % phone_id, phone=None)
    # db.update(_table, where="id=%i" % card_id, phone=phone_user[0].phone)

    try:
        # 转移记录
        db.update(record_table, where="lost_id=%i" % phone_id, lost_id=card_id)
        db.update(record_table, where="find_id=%i" % phone_id, find_id=card_id)
        # 删除合并用户
        phone_user = db.select(_table, where="id=%i" % phone_id, limit=1, what='phone')
        try:
            db.delete(_table, where="id=%i" % phone_id)
        except:
            db.update(_table, where="id=%i" % phone_id, phone=None)
        db.update(_table, where="id=%i" % card_id, phone=phone_user[0].phone)
    except:
        t.rollback()
        return False
    else:
        t.commit()
        return card_id
Ejemplo n.º 4
0
def delete_record():
    aid = request.cookies.get('aid')
    if aid is None or aid == "":
        return redirect(url_for("login.sign_in"))

    old_amt = float(request.form.get('old_amt'))
    t = request.form.get('time')
    db.delete(conn, 'records', {'reid': request.form.get('reid')})

    # influence plans
    if t == "":
        record_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    else:
        record_time = t
    sql = """select * from plans where aid = '%s' and (ending > '%s' or ending is null);""" % (
        aid, record_time)
    plans = db.special_select(sql)
    for plan in plans:
        if check_time(
                plan['starting'].strftime("%Y-%m-%d %H:%M:%S").split(" ")[0],
                record_time.split(" ")[0], plan['cycle']):
            new_credit = float(plan['credit']) - old_amt
            db.update(conn, "plans", {"=": {
                'credit': new_credit
            }}, {'pid': plan['pid']})

    # influence win_honor
    valid_honor(conn, aid)

    return redirect(url_for(".all_records"))
Ejemplo n.º 5
0
    def POST(self):
        if (web.config._session.roleid != 1):
            raise web.seeother('/')
        pdata = web.input(item=None, action=None, picture={}, category_id=None)
        if pdata.action == "create":
            fullpath=None
            if 'picture' in pdata:#what I added for storing the picture
                if len(pdata.picture.filename)>0:
                    filedir='./static'
                    filepath=pdata.picture.filename.replace('\\','/')
                    filename=filepath.split('/')[-1]
		    fullpath=filedir+'/'+filename
                    fout=open(fullpath,'wb')
                    fout.write(pdata.picture.file.read())
                    fout.close()
            create_item(pdata.item, pdata.description, pdata.price,fullpath)
        elif pdata.action == 'delete':
            if len(pdata.picture)>0:
                os.remove(pdata.picture)
            delete_item(pdata.item)
        elif pdata.action == 'hide':
            set_status(pdata.item, False)
        elif pdata.action == 'show':
            set_status(pdata.item, True)
        elif pdata.action == 'update':
            db.update('MenuItems', where='id=$pdata.item', vars=locals(), price=pdata.price)
        elif pdata.action == 'category':
            db.insert('Item_Categories', item_id = pdata.item, category_id = pdata.category_id)
        elif pdata.action == 'delete_category':
            db.delete('Item_Categories', vars=locals(), where= 'item_id = $pdata.item and category_id = $pdata.category_id')
        raise web.seeother('/menu_editor')
Ejemplo n.º 6
0
 def POST(self):
     pdata = web.input(category_id=None)
     print pdata.category_id
     db.delete('Categories', vars=locals(), where="id = $pdata.category_id")
     items = get_menu_items()
     tags = db.select('Categories').list()
     menu_table = render.menu_editor(items, tags)
     return render_page(menu_table)
Ejemplo n.º 7
0
def remove(quote_id):
    quote = db.get(quote_id)
    if quote is None:
        abort(404)
    if request.provided_json():
        return json_nyi()
    db.delete(quote)
    return "success"
Ejemplo n.º 8
0
 def setUp(self):
     db.delete('MenuItems', where='1=1')
     self.input_mock = MagicMock()
     self.winput = patch('web.input')
     self.config_mock = MagicMock()
     self.config = patch('web.config', new=self.config_mock)
     self.config_mock._session.roleid = 1
     self.menued = menu()
Ejemplo n.º 9
0
def remove(quote_id):
    if not 'user' in session:
        abort(403)
    quote = db.get(quote_id)
    if quote is None:
        abort(404)
    if request.provided_json():
        return json_nyi()
    db.delete(quote)
    return "success"
Ejemplo n.º 10
0
 def setUp(self):
     self.passwd = "$2a$12$CyLyLDPA5NFTY48o3fANQOEsni38JgHBk3FNwdUFd1OwYMBZxN146" 
     db.delete('Users', where='id > 0')
     self.uid = db.insert('Users', uname='kevin', role=1, password=self.passwd)
     self.input_mock = MagicMock()
     self.winput = patch('web.input')
     self.config_mock = MagicMock()
     self.config = patch('web.config', new=self.config_mock)
     self.login_web = login()
     self.logout_web = logout()
Ejemplo n.º 11
0
def remove(quote_id):
    if not 'user' in session:
        abort(403)
    quote = db.get(quote_id)
    if quote is None:
        abort(404)
    if request.provided_json():
        return json_nyi()
    db.delete(quote)
    return "success"
Ejemplo n.º 12
0
 def setUp(self):
     db.delete('Users', where='id > 0')
     self.input_mock = MagicMock()
     self.winput = patch('web.input')
     self.input_mock.uname = 'kevin'
     self.input_mock.utype = 1
     self.input_mock.pword = 'password'
     self.config_mock = MagicMock()
     self.config = patch('web.config', new=self.config_mock)
     self.config_mock._session.roleid = 1
     self.manager = manager()
Ejemplo n.º 13
0
    def execute_edit_comment(self, request, **kwargs):
        comment = db.query(Comment).get(kwargs["id"])
        if request.user and request.user.id == comment.identity.user.id:
            if db.query(Comment).filter(Comment.content_item_id == comment.content_item_id, Comment.created_at > comment.created_at).count() > 0:
                response = {"error" : u"К сожалению, пока вы редактировали комментарий, его успели увидеть другие пользователи. Обновите страницу, чтобы увидеть их реакцию на ваш позор."}
            else:
                if (request.form["text"].strip() == ""):
                    db.delete(comment)
                    response = {"deleted" : True}
                else:
                    comment.text = request.form["text"]
                    response = {"text" : self._process_comment_text(comment.text)}
                db.flush()

            return Response(simplejson.dumps(response), mimetype="application/json")

        raise Forbidden()
Ejemplo n.º 14
0
    def execute_callback(self, request, **kwargs):
        result = self.services[kwargs["service"]].oauth_callback(request)
        if result:
            identity = db.query(Identity).filter(Identity.service == kwargs["service"], Identity.service_id == result[0]).first()
            if identity is None:
                identity = Identity()
                identity.service = kwargs["service"]
                identity.service_id = result[0]
                identity.service_data = result[1]
                db.add(identity)
                db.flush()
            else:
                identity.service_data = result[1]
                db.flush()
            if not identity.trusted and (identity.trust_last_checked is None or
                    identity.trust_last_checked < datetime.now() - timedelta(minutes=10)):
                service = self.services[kwargs["service"]]
                identity.trusted = hasattr(service, "is_trusted") and service.is_trusted(identity.service_data)
                identity.trust_last_checked = datetime.now()
                db.flush()
            if identity.user is None:
                if request.user is None:
                    identity.user = User()
                    identity.user.default_identity_id = identity.id # identity.user.default_identity = identity causes CircularDependencyError
                    identity.user.token = "".join(random.choice(string.letters + string.digits + string.punctuation)
                                                  for i in xrange(32))
                    identity.user.url_token = "".join(random.choice(string.letters + string.digits + string.punctuation)
                                                      for i in xrange(32))
                    identity.user.settings = {}
                    db.add(identity.user)
                    db.flush()
                else:
                    identity.user = request.user
                    db.flush()
            else:
                if request.user is not None and request.user is not identity.user:
                    for other_identity in request.user.identities:
                        other_identity.user = identity.user
                    db.delete(request.user)
                    db.flush()

            response = redirect(request.args.get("from", "/"))
            response.set_cookie("u", identity.user.token, expires=datetime.now() + timedelta(days=365))
            return response
        else:
            raise Unauthorized()
Ejemplo n.º 15
0
def run_in_pool(fn, iterable, desc="", pool_size=4, debug=False):
    items = list(iterable)

    if debug:
        # Run in same process for debug mode
        [fn(item) for item in items]
        return

    pool = Pool(pool_size)

    monitor_name = f"run_in_pool|{uuid4().hex}"
    monitor = Process(target=_monitor, args=(monitor_name, len(items), desc))

    fn = curry(_run, fn, monitor_name)
    monitor.start()

    try:
        return list(pool.imap(fn, items))
    finally:
        db.delete(monitor_name)
        monitor.terminate()
Ejemplo n.º 16
0
    def setUp(self):
        db.delete('Orders', where='1=1')
        db.delete('OrderedItems', where='1=1')
        db.delete("MenuItems", where='1=1')
        db.insert('MenuItems', id=1, name='Chicken', description='Chicken', price=20)
        self.torders = new_order()
	self.titems = new_item()
	self.tquant = new_quantity()
        self.config_mock = MagicMock()
        self.config = patch('web.config', new=self.config_mock)
        self.config_mock._session.roleid = 2
Ejemplo n.º 17
0
def delete(key):
    doc = db["document/" + key]
    db.delete(doc)
    return jsonify({"status": "ok"})
Ejemplo n.º 18
0
 def setUp(self):
     self.passwd = "$2a$12$CyLyLDPA5NFTY48o3fANQOEsni38JgHBk3FNwdUFd1OwYMBZxN146" 
     db.delete('Users', where='id > 0')
Ejemplo n.º 19
0
 def tearDown(self):
     db.delete('Users', where='id=$uid', vars=dict(uid=self.uid))
Ejemplo n.º 20
0
 def setUp(self):
     self.passwd = "$2a$12$CyLyLDPA5NFTY48o3fANQOEsni38JgHBk3FNwdUFd1OwYMBZxN146" 
     db.delete('Users', where='id > 0')
     self.uid = db.insert('Users', uname='kevin', role=1, password=self.passwd)
     self.uinfo = users.user_info()
Ejemplo n.º 21
0
def test_successful_delete(rethink_connect):
    global unique_id
    result = delete(database, table, unique_id, rethink_connect)
    assert result is not None
    assert len(result) is 1
    assert result['objects_deleted'] is 1
Ejemplo n.º 22
0
def del_user(uname):
    db.delete("Users", vars=dict(uname=uname), where="uname=$uname")
Ejemplo n.º 23
0
 def GET(self):
     db.delete('user', where="id>0")
     db.delete('data', where="id>0")
     web.setcookie('user', '', 3600)
     web.setcookie('color', '', 3600)
     return render.bye()
Ejemplo n.º 24
0
 def setUp(self):
     db.delete('MenuItems', where='1=1')
     self.menued = menu()
Ejemplo n.º 25
0
async def data_manager(websocket, path):
    logging.info(f'[INFO] Current path: {str(path)}')
    try:
        if path is '/':
            raise Exception(f'No operation defined on the current path.'
                            f'\nReceived path: {str(path)}')
        data = await websocket.recv()
        data = json.loads(data)

        identifier = data['id']
        request_type = data['type']
        payload = data['payload']
        time = data['time']
        logging.info(f'[INFO] Data received: {data}')

        if request_type != RDM_CALL:
            raise Exception(f'Type of service not as expected. Probably a call'
                            f'for other service. Verify logs for further infor'
                            f'mation!')

        if save_audit(identifier, request_type, payload, time):
            pass
        else:
            logging.error(f'[ERROR] Error while trying to save data to audit'
                          f' database. Verify Rethink Data Manager logs for '
                          f'furhter information!')

        try:
            connection = configure_database(
                    ReDB_HOST,
                    ReDB_PORT,
                    ReDB_DEFAULT_DB,
                    ReDB_USER,
                    ReDB_PASS
                )

            if str(path) == op[1]:
                database = payload['database']
                table = payload['table']
                payload = payload['data']
                logging.info(f'[INFO] Inserting data:\n\tDATABASE: '
                             f'{database}\n\tTABLE: {table}\n\tDATA: '
                             f'{payload}')
                result = insert(database, table, payload, connection)
                if result == {}:
                    raise Exception(f'[ERROR] Error trying to insert data. '
                                    f'Verify the logs for the full traceback. '
                                    f'The data was not inserted!')
                else:
                    await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[2]:
                database = payload['database']
                table = payload['table']
                logging.info(f'[INFO] Getting all data:\n\tDATABASE: '
                             f'{database}\n\tTABLE: {table}')
                result = get_all(database, table, connection)
                if result == {}:
                    raise Exception(f'[ERROR] Error trying to getting data. '
                                    f'Verify the logs for the full traceback. '
                                    f'Neither the table is empty or no table'
                                    f' was found!')
                else:
                    await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[3]:
                database = payload['database']
                table = payload['table']
                identifier = payload['identifier']
                logging.info(f'[INFO] Getting objetct data:\n\tDATABASE: '
                             f'{database}\n\tTABLE: {table}\n\tIDENTIFIER: '
                             f'{identifier}')
                result = get(database, table, identifier, connection)
                if result == {}:
                    raise Exception(f'[ERROR] Error trying to getting data. '
                                    f'Verify the logs for the full traceback. '
                                    f'Neither the object doesn\'t exists or no'
                                    f' table was found!')
                else:
                    await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[4]:
                database = payload['database']
                table = payload['table']
                identifier = payload['identifier']
                statment = payload['data']
                logging.info(f'[INFO] Updating object:\n\tDATABASE: '
                             f'{database}\n\tTABLE: {table}\n\tIDENTIFIER: '
                             f'{identifier}\n\tUPDATE STATEMENT: {statment}')
                result = update(
                    database,
                    table,
                    identifier,
                    statment,
                    connection
                    )
                if result == {}:
                    raise Exception(f'[ERROR] Error trying to update object. '
                                    f'Verify the logs for the full traceback. '
                                    f'Neither the object doesn\'t exists or no'
                                    f' table was found!')
                elif result['objects_updated'] is 0:
                    raise Exception(f'[ERROR] Error trying to update object. '
                                    f'Verify the logs for the full traceback.')
                else:
                    await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[5]:
                database = payload['database']
                table = payload['table']
                identifier = payload['identifier']
                logging.info(f'[INFO] Deleting object:\n\tDATABASE: '
                             f'{database}\n\tTABLE: {table}\n\tIDENTIFIER: '
                             f'{identifier}')
                result = delete(database, table, identifier, connection)
                if result == {}:
                    raise Exception(f'[ERROR] Error trying to delete object. '
                                    f'Verify the logs for the full traceback. '
                                    f'Neither the object doesn\'t exists or no'
                                    f' table was found!')
                elif result['objects_deleted'] is 0:
                    raise Exception(f'[ERROR] Error trying to delete object. '
                                    f'Verify the logs for the full traceback.')
                else:
                    await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[6]:
                pass
            # database = payload['database']
            # table = payload['table']
            # logging.info(f'[INFO] Deleting all objects:\n\tDATABASE: '
            #              f'{database}\n\tTABLE: {table}')
            # result = delete_all(database, table, connection)
            # if result == {}:
            #     raise Exception(f'[ERROR] Error trying to delete objects. '
            #                     f'Verify the logs for the full traceback. '
            #                     f'Neither some error was found or no table'
            #                     f' was found!')
            # elif result['objects_deleted'] is 0:
            #     raise Exception(f'[ERROR] Error trying to delete object. '
            #                     f'Verify the logs for the full traceback.')
            # else:
            #     await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[7]:
                pass
                # database = payload['database']
                # table = payload['table']
                # logging.info(f'[INFO] Creating new table:\n\tDATABASE: '
                #              f'{database}\n\tTABLE: {table}')
                # result = create_table(database, table, connection)
                # if result == {}:
                #     raise Exception(f'[ERROR] Unknown error while trying to '
                #                     f'create a new table. Verify the logs'
                #                     f' for the the full traceback.')
                # elif result['tables_created'] is 0:
                #     raise Exception(f'[ERROR] This table ({table})'
                #                     f' already exists!')
                # else:
                #     await websocket.send(json.dumps(success_msg(result)))
            elif str(path) == op[8]:
                database = payload['database']
                table = payload['table']
                statment = payload['filter']
                statment = json.loads(statment)
                logging.info(f'[INFO] Getting objetct data:\n\tDATABASE: '
                             f'{database}\n\tTABLE: {table}\n\tFILTER: '
                             f'{statment}')
                result = get_where(database, table, statment, connection)
                if result == {}:
                    raise Exception(f'[ERROR] Unknown error while trying to '
                                    f'create a new table. Verify the logs'
                                    f' for the the full traceback.')
                else:
                    await websocket.send(json.dumps(success_msg(result)))
            else:
                raise Exception(f'Unknown operation on the current path.'
                                f'\nReceived path: {str(path)}')
        except Exception as err:
            if connection:
                disconnect_database(connection)
                raise err
        except KeyboardInterrupt as err:
            disconnect_database(connection)
            raise err
        except ConnectionClosed as err:
            disconnect_database(connection)
            raise err
        except CancelledError as err:
            disconnect_database(connection)
            raise err
    except Exception as err:
        logging.error(f'[ERROR] Error at services/data_manager.'
                      f'\nTraceback: {err}')
        await websocket.send(json.dumps(
            error_msg(path)
        ))
    else:
        pass
Ejemplo n.º 26
0
def delete_receipt(order_no):
    args = dict(order_no=order_no)
    db.delete("Receipts", vars=args, where="order_id=$order_no")
Ejemplo n.º 27
0
def delete_server(image=None):
    '''Delete a server by image_id'''
    return db.delete('server', where="image=$image", vars=locals())
Ejemplo n.º 28
0
# coding=utf-8
Ejemplo n.º 29
0
 def tearDown(self):
     db.delete('Orders', vars=dict(oid=self.oid), where="id=$oid")
Ejemplo n.º 30
0
 def tearDown(self):
     for x in xrange(0,5):
         db.delete('Orders', vars=dict(oid=self.olist[x]), where="id=$oid")
Ejemplo n.º 31
0
 def delete(self, directory, key):
     kv = db.query(KV).filter_by(directory=directory, key=key).first()
     if kv is None:
         raise KeyError
     db.delete(kv)
     db.flush()
Ejemplo n.º 32
0
def delete_item( item_id):
    db.delete('MenuItems', vars=locals(), where="id=$item_id")
Ejemplo n.º 33
0
def delete_item(order, item):
    args = dict(order=order, item=item)
    db.delete("OrderedItems", vars=args, where='order_id = $order and item_id = $item')
Ejemplo n.º 34
0
# coding=utf-8
Ejemplo n.º 35
0
def delete_pending_server(id=None):
    return db.delete('server', where="id=$id", vars=locals())