Esempio n. 1
0
    def test_check_schema(self):
        db.remove()
        if self.latest != 0:
            assert not db.check_schema()

        db.update_schema()
        assert db.check_schema()
Esempio n. 2
0
 def test_db(self):
   
     id = db.find_and_modify({'url':'https://github.com/okamuuu'}, {'url':'https://github.com/okamuuu'})
     url = db.find_one({'url':'https://github.com/okamuuu'})
     self.assertTrue(url)
    
     ### clean up
     db.remove({'_id':url['_id']})
Esempio n. 3
0
def remove_song(song_id):
    """Main function for removing a song from the DB"""
    try:
        db.remove(song_id)
    except:
        print(f"Failed removing the song with the id {song_id}")

    pass
Esempio n. 4
0
def delete(files, ignore):
    handler = PathHandler(ignore)
    digest = hashfile(path)
    files = db.get(digest)
    if len(files) >= 2:
        os.remove(path)
        db.remove(digest, path)
    elif len(files) == 1 and path not in files:
        os.remove(path)
    else:
        print('%s is not duped, count: %d' % (path, len(files)))
Esempio n. 5
0
def controll(i):
    if i in [0, 7]:
        i = input('Sure to exit..[y/m] ').strip().lower()
        if i == 'y':
            db.close()
            exit()
        else:
            print('Exit Canceled.')
    elif i == 1:
        book = input('Name of book-> ')
        author = input('Author of book-> ')
        try:
            qty = int(input('Quantity purchased-> ').strip())
        except:
            print('Input should be integer for quantity.')
            print('Retry the purchase entry (1).')
            return
        db.purchase(book, author, qty)
    elif i == 2:
        s_name = input('Student Getting Name-> ').strip()
        s_class = input("Class of Student-> ").strip()
        s_id = input('Id of Student-> ').strip()
        b_name = input('Nmae of book issued-> ').strip()
        b_author = input('Author of Issued book-> ').strip()
        db.issue(b_name, b_author, s_name, s_class, s_id)
    elif i == 3:
        bname = input('Nmae of book returned-> ').strip()
        bauthor = input('Author of book returned-> ').strip()
        sid = int(input('Id of student returned book-> ').strip())
        db.book_back(bname, bauthor, sid)
    elif i == 4:
        bname = input('Nmae of book removed-> ').strip()
        bauthor = input('Author of book removed-> ').strip()
        bqty = int(input('Quantity of book removed-> ').strip())
        breason = int(input('Reason for removal-> ').strip())
        db.remove(bname, bauthor, bqty, reason)

    elif i in (50, 5):
        db.all_books()
    elif i == 51:
        db.books()
    elif i in (60, 6):
        db.all_issued()
    elif i == 61:
        db.issued()

    for a in range(1, 21):
        print()
        time.sleep(1 / a)
    print()
Esempio n. 6
0
def delstatus():
    if request.method == 'POST':
        entry = request.form[entry]
        #Get the active directory username
        user = request.headers.get('REMOTE_USER')
        #place the new monitored region in the DB
        result = db.remove(entry)
        return render_template("delstatus.html", result=result)
Esempio n. 7
0
def settings():
    # Add Candidate Form
    if request.method == "POST":
        if "insert" in request.form:
            name = request.form["candName"]
            bio = request.form["candBio"]
            image = request.form["filename"]
            error = None

            if not name or not bio or not image:
                error = "Missing Information"

            if error is not None:
                flash(error)
            else:
                insert("candidate", ["name", "bio", "img"], [name, bio, image])
                return render_template('index.html', alert="insert")

        # Remove a Candidate Form
        elif "delete" in request.form:
            candName = request.form["candName"]
            remove("candidate", "name", candName)
            return render_template('index.html', alert="delete")

        # Seetings Form
        elif "settings" in request.form:
            db = get_db()
            realign = request.form["realign"]
            numPeople = request.form["people"]
            error = None

            if not numPeople:
                error = "Missing Information"

            if error is not None:
                flash(error)
            else:
                insert("settings", ["realign", "numPeople"],
                       [realign, numPeople])
                return render_template('index.html', alert="settings")

    # Main Page
    return render_template('index.html')
Esempio n. 8
0
 def test_latest_schema(self):
     assert_eq(db.latest_schema(), self.latest)
     db.remove()
     assert_eq(db.latest_schema(), 0)
Esempio n. 9
0
    def test_list_tables(self):
        assert 'schema_table' in db.list_tables()

        db.remove()
        assert_eq(db.list_tables(), [])
Esempio n. 10
0
    def POST(self, action):
        if action == "upload_photo":
            # this is to prevent IE from downloading the JSON.
            web.header("Content-Type", "text/plain")
        else:
            web.header("Content-Type", "application/json")
        set_no_cache()

        # check if we have the action
        if action not in self.POST_ACTIONS:
            return error.wrong_action()

        # get the input data if we have the spec
        if action in self.VALIDATE_SPECS:
            d = get_input(self.VALIDATE_SPECS[action])

        # act
        if action == "register":
            return jsond(db.register(d.uid, d.email, d.password))
        elif action == "login":
            u = db.checkLogin(d.uid, d.password)
            if u:
                session.uuid = str(u["_id"])
                return jsond({"uid": u["uid"]})
            else:
                return error.wrong_login()

        # check login
        uuid = session.get("uuid", None)
        if not uuid:
            return error.not_logged_in()

        if action == "follow":
            return jsond(db.follow(uuid, d.uid))

        elif action == "unfollow":
            return jsond(db.unfollow(uuid, d.uid))

        elif action == "publish":
            req = spec.extract(self.EXTRACT_SPECS["publish_request"], d)
            return jsond(db.publish(uuid, **req))

        elif action == "remove":
            req = spec.extract(self.EXTRACT_SPECS["remove_request"], d)
            return jsond(db.remove(uuid, **req))

        elif action == "update_profile":
            u = db.update_profile(uuid, d)
            return jsond(spec.extract(self.EXTRACT_SPECS["current_user"], u))

        elif action == "upload_photo":
            try:
                d = web.input(photo={})
                if "photo" in d:
                    u = db.get_user(uuid)
                    photo.resize_save(u["uid"], d.photo.file)
                    if db.update_photo(uuid, True).has_key("success"):
                        return jsond({"success": 1})
                return error.photo_upload_failed()
            except Exception, e:
                traceback.print_exc()
                return error.photo_upload_failed()
Esempio n. 11
0
 def test_remove(self):
     db.remove(self.db_conn, '/tmp/video1')
Esempio n. 12
0
 def teardown():
     db.remove()
Esempio n. 13
0
 def teardown(self):
     self.db.close()
     db.remove()
Esempio n. 14
0
def remove(name):
    db.remove(name)
Esempio n. 15
0
    def POST(self, action):
        if action == 'upload_photo':
            # this is to prevent IE from downloading the JSON.
            web.header('Content-Type', 'text/plain')
        else:
            web.header('Content-Type', 'application/json')
        set_no_cache()

        # check if we have the action
        if action not in self.POST_ACTIONS:
            return error.wrong_action()

        # get the input data if we have the spec
        if action in self.VALIDATE_SPECS:
            d = get_input(self.VALIDATE_SPECS[action])

        # act
        if action == 'register':
            return jsond(db.register(d.uid, d.email, d.password))
        elif action == 'login':
            u = db.checkLogin(d.uid, d.password)
            if u:
                session.uuid = str(u['_id'])
                return jsond({'uid': u['uid']})
            else:
                return error.wrong_login()

        # check login
        uuid = session.get('uuid', None)
        if not uuid:
            return error.not_logged_in()

        if action == 'follow':
            return jsond(db.follow(uuid, d.uid))

        elif action == 'unfollow':
            return jsond(db.unfollow(uuid, d.uid))

        elif action == 'publish':
            req = spec.extract(self.EXTRACT_SPECS['publish_request'], d)
            return jsond(db.publish(uuid, **req))

        elif action == 'remove':
            req = spec.extract(self.EXTRACT_SPECS['remove_request'], d)
            return jsond(db.remove(uuid, **req))

        elif action == 'update_profile':
            u = db.update_profile(uuid, d)
            return jsond(spec.extract(self.EXTRACT_SPECS['current_user'], u))

        elif action == 'upload_photo':
            try:
                d = web.input(photo={})
                if 'photo' in d:
                    u = db.get_user(uuid)
                    photo.resize_save(u['uid'], d.photo.file)
                    if db.update_photo(uuid, True).has_key('success'):
                        return jsond({'success': 1})
                return error.photo_upload_failed()
            except Exception, e:
                traceback.print_exc()
                return error.photo_upload_failed()
Esempio n. 16
0
def remove_show(day, start, end):
    try:
        db.remove([day, start, end])
    except IndexError:
        pass
    return redirect(url_for("schedule"))
Esempio n. 17
0
def long_pool():
    last_uid = 0

    first_step = True
    worker_flag = False
    edit_flag_1 = False
    edit_flag_11 = False
    edit_flag_12 = False
    edit_flag_13 = False

    worker_user_id = 0
    worker_chat_id = 0
    edit_user_id = 0
    edit_chat_id = 0

    requested_doc = {}

    while True:
        if first_step:
            obj_ = get_last_obj()
        else:
            obj_ = get_last_obj(current_uid + 1)

        if not obj_:
            continue

        current_uid = obj_['update_id']

        if current_uid != last_uid:
            last_uid = current_uid
            if first_step:
                first_step = False

            if edit_flag_11 or edit_flag_12 or edit_flag_13:
                response_edit_message_obj = command_message_handler(
                    obj_, 'response_edit')
                if response_edit_message_obj:
                    text = response_edit_message_obj['text']

                    answer_text = ''
                    if edit_flag_11 or edit_flag_12:
                        try:
                            text = json.loads(text)

                            if isinstance(text, dict):
                                if text.get('position'):
                                    for value in list(text.values()):
                                        if not isinstance(value, str):
                                            raise ValueError

                                    if edit_flag_11:
                                        if not db.insert(text):
                                            time.sleep(1.5)
                                            if not db.insert(text):
                                                answer_text = 'Ошибка ' +\
                                                    'добавления, ' +\
                                                    'попробуйте ещё раз'
                                            else:
                                                answer_text = 'Добавление ' +\
                                                    'прошло успешно'
                                        else:
                                            answer_text = 'Добавление ' +\
                                                'прошло успешно'

                                    elif edit_flag_12:
                                        if not db.edit(text['position'], text):
                                            time.sleep(1.5)
                                            if not db.edit(
                                                    text['position'], text):
                                                answer_text = 'Ошибка ' +\
                                                    'изменения, попробуйте ' +\
                                                    'ещё раз'
                                            else:
                                                answer_text = 'Изменение ' +\
                                                    'прошло успешно'
                                        else:
                                            answer_text = 'Изменение ' +\
                                                'прошло успешно'
                                else:
                                    answer_text = 'Некорректный ввод'
                            else:
                                answer_text = 'Некорректный ввод'
                        except ValueError:
                            answer_text = 'Некорректный ввод'
                    elif edit_flag_13:
                        if text:
                            if not db.remove(text):
                                time.sleep(1.5)
                                if not db.remove(text):
                                    answer_text = 'Ошибка удаления, ' +\
                                        'попробуйте ещё раз'
                                else:
                                    answer_text = 'Удаление прошло успешно'
                            else:
                                answer_text = 'Удаление прошло успешно'

                    bot_request(
                        'sendMessage', 'chat_id=' + str(edit_chat_id),
                        'parse_mode=HTML', 'text=' + answer_text,
                        'reply_to_message_id=' +
                        str(edit_message_obj['message_id']))

                worker_flag = False
                edit_flag_1 = False
                edit_flag_11 = False
                edit_flag_12 = False
                edit_flag_13 = False
                edit_user_id = 0
                edit_chat_id = 0

            elif edit_flag_1:
                edit_message_obj = command_message_handler(obj_, 'edit')
                if edit_message_obj:
                    if edit_user_id == edit_message_obj['user_id'] \
                            and edit_chat_id == edit_message_obj['chat_id']:
                        sub_edit_flag_11 = False
                        sub_edit_flag_12 = False
                        sub_edit_flag_13 = False
                        if edit_message_obj['text'] == 'Вставить':
                            response = '<b>Введите данные в формате ' +\
                                'json-словаря.</b>\nШаблон: \n' + \
                                '{\n' + \
                                '\t"position": "Поле должности ' +\
                                'является обязательным",\n' + \
                                '\t"office": "A 101",\n' + \
                                '\t"surname": "Иванов",\n' + \
                                '\t"name": "Иван",\n' + \
                                '\t"middle_name": "Иванович",\n' + \
                                '\t"email": "*****@*****.**",\n' + \
                                '\t"phone": "8 (423) 212 34 55"\n' + \
                                '}'
                            sub_edit_flag_11 = True
                        elif edit_message_obj['text'] == 'Изменить':
                            response = '<b>Введите новые данные в формате ' +\
                                'json-словаря.</b>\nШаблон: \n' + \
                                '{\n' + \
                                '\t"position": "Поле должности ' +\
                                'является обязательным",\n' + \
                                '\t"office": "A 101",\n' + \
                                '\t"surname": "Иванов",\n' + \
                                '\t"name": "Иван",\n' + \
                                '\t"middle_name": "Иванович",\n' + \
                                '\t"email": "*****@*****.**",\n' + \
                                '\t"phone": "8 (423) 212 34 55"\n' + \
                                '}'
                            sub_edit_flag_12 = True
                        elif edit_message_obj['text'] == 'Удалить':
                            response = '<b>Введите должность, данные по ' +\
                                'которой хотите удалить.</b>'
                            sub_edit_flag_13 = True
                        else:
                            continue

                        bot_request(
                            'sendMessage', 'chat_id=' + str(edit_chat_id),
                            'parse_mode=HTML', 'text=' + str(response),
                            'reply_to_message_id=' +
                            str(edit_message_obj['message_id']))
                        worker_flag = False
                        edit_flag_1 = False

                        if sub_edit_flag_11:
                            edit_flag_11 = True
                        if sub_edit_flag_12:
                            edit_flag_12 = True
                        if sub_edit_flag_13:
                            edit_flag_13 = True
                        edit_user_id = message_obj['user_id']
                        edit_chat_id = message_obj['chat_id']
                else:
                    worker_flag = False
                    edit_flag_1 = False
                    edit_flag_11 = False
                    edit_flag_12 = False
                    edit_flag_13 = False
                    edit_user_id = 0
                    edit_chat_id = 0

            elif worker_flag:
                worker_message_obj = command_message_handler(obj_, 'worker')
                if worker_message_obj:
                    if worker_user_id == worker_message_obj['user_id'] \
                            and worker_chat_id == worker_message_obj[
                                'chat_id']:
                        if worker_message_obj['text'] == 'Только ФИО':
                            response = str(
                                '<b>Фамилия</b>: ' +
                                f'{requested_doc.get("surname")}\n' +
                                '<b>Имя</b>: ' +
                                f'{requested_doc.get("name")}\n' +
                                '<b>Отчество</b>: ' +
                                f'{requested_doc.get("middle_name")}\n')
                        elif worker_message_obj['text'] == 'Всё':
                            response = ''
                            for key, val in requested_doc.items():
                                if key == 'position':
                                    key = 'Должность'
                                elif key == 'office':
                                    key = 'Кабинет'
                                elif key == 'surname':
                                    key = 'Фамилия'
                                elif key == 'name':
                                    key = 'Имя'
                                elif key == 'middle_name':
                                    key = 'Отчество'
                                elif key == 'email':
                                    key = 'Почта'
                                elif key == 'phone':
                                    key = 'Телефон'
                                else:
                                    continue

                                response += f'<b>{str(key)}</b>: {val}\n'
                            if not response:
                                response = None
                        else:
                            continue

                        bot_request(
                            'sendMessage', 'chat_id=' + str(worker_chat_id),
                            'parse_mode=HTML', 'text=' + str(response),
                            'reply_to_message_id=' +
                            str(worker_message_obj['message_id']))
                        worker_flag = False
                        edit_flag_1 = False
                        worker_user_id = 0
                        worker_chat_id = 0
                else:
                    worker_flag = False
                    edit_flag_1 = False
                    edit_flag_11 = False
                    edit_flag_12 = False
                    edit_flag_13 = False
                    edit_user_id = 0
                    edit_chat_id = 0

            else:
                message_obj = message_handler(obj_)
                if message_obj:
                    if message_obj['edit']:
                        if not show_edit_keyboard(message_obj):
                            continue
                        edit_flag_1 = True
                        edit_user_id = message_obj['user_id']
                        edit_chat_id = message_obj['chat_id']
                    if message_obj['list']:
                        data = list(db.collection.find({}))
                        text = '<b>Список имеющихся должностей:</b>\n'
                        if data:
                            for doc in data:
                                text += str(doc['position'] + ';\n')

                        bot_request(
                            'sendMessage',
                            'chat_id=' + str(message_obj['chat_id']),
                            'parse_mode=HTML', 'text=' + text,
                            'reply_to_message_id=' +
                            str(message_obj['message_id']))
                    else:
                        data = list(db.collection.find({}))

                        requested_doc = None
                        if data:
                            for doc in data:
                                position = doc['position'].lower().strip()
                                if position == message_obj['text']:
                                    requested_doc = doc
                                    break

                        if requested_doc:
                            show_worker_keyboard(message_obj)
                            worker_flag = True
                            worker_user_id = message_obj['user_id']
                            worker_chat_id = message_obj['chat_id']