Exemple #1
0
	def read_object(self, filename, password = None): 
		"""read a note, return text"""
		self.db = self.check_connection()
		notebookplusuid = self.helper.split_filename(filename)
		notebook = notebookplusuid[0]
		uid = notebookplusuid[1]
		collection = self.db[notebook]
		all_note_data = collection.find_one({'_id' : uid })
		try: 
			title = all_note_data['title']
			if password:
                                title = encryption.decrypt_text(title, password)
		except TypeError:
			notedata = self.helper.add_note(collection, uid, password)
			if all_note_data: # happens when a notebook has no notes
				all_note_data = collection.find_one({'_id' : notedata[1] })
				title = all_note_data['title']
				if password:
                                        title = encryption.decrypt_text(title, password)
			else: False
		try:
                        main = all_note_data['body']
                except TypeError:
                        print "empty note body"
		if password:
                        main = encryption.decrypt_text(main, password)
		try:
                        text = title+'\n'+ main
                        return text
                except UnboundLocalError: # when a note was created
                        None # FIXME
Exemple #2
0
def updateMongDB():

    post = collection.find_one({"name": "songck"})
    print 'post["token_time"]', post["token_time"]

    now_diff = datetime.datetime.utcnow() - post["token_time"]
    print 'now_diff', now_diff

    time_out = datetime.timedelta(hours=1)
    if now_diff > time_out:
        print "证书超时。"

    db_get = collection.find_one({"_id": post["_id"]})
    print(db_get)
    print db_get["_id"]
Exemple #3
0
 def _find_job(self, _id, collection):
     # internal method used by .load_job and .find_job
     doc = collection.find_one({"_id": _id})
     if doc is None:
         raise core4.error.CoreJobNotFound("job [{}] not found".format(_id))
     job = self.job_factory(doc["name"]).deserialise(**doc)
     return job
Exemple #4
0
def get_flight_by_id(flight_id: str):
    global client
    try:
        db = client['flight']
        collection = db['flightCollection']
        # flights = [flight for flight in collection.find({})]
        flight = collection.find_one({'_id': ObjectId(flight_id)})
        flight['_id'] = str(flight['_id'])
        db = client['route']
        collection = db['routeCollection']
        route = collection.find_one({'_id': flight['route_id']})
        flight['route_id'] = str(flight['route_id'])
        flight['source_city'] = route['source_city']
        flight['dest_city'] = route['dest_city']

        return flight
    except Exception as e:
        print('Exception in get flight by id: ' + str(e))
Exemple #5
0
def get_tickets_left(flight_id: str, date: str):
    global client
    try:
        db = client['ticket']
        collection = db['ticketCollection']
        flight_entry = collection.find_one({'flight_id': ObjectId(flight_id)})
        flight_ticket = flight_entry['tickets_array']
        tickets_left = flight_ticket.get(date)

        if tickets_left is None:
            db = client['flight']
            collection = db['flightCollection']
            # flights = [flight for flight in collection.find({})]
            flight = collection.find_one({'_id': ObjectId(flight_id)})
            return {'e_left': flight['e_seats'], 'b_left': flight['b_seats']}
        return tickets_left

    except Exception as e:
        print('Exception in get tickets left: ' + str(e))
Exemple #6
0
    def find_one(self, table, dic):
        '''
        :param table: str 数据库中的集合
        :param dic: dict 查询条件
        :return: dict 返回单条记录的字典
        '''
        collection = self.db[table]
        rep = collection.find_one(dic)

        return rep
Exemple #7
0
def add_gsm_run(collection, material, directory, other_info={}, other_files = [], force=False):
    (db, fs, client) = load_db()
    collection = db[collection]
    images = []
    energies = []
    image_dir = [x for x in os.listdir('scratch') if fnmatch.fnmatch(x, 'IMAGE.*')]
    image_dir.sort()
    for dir in image_dir:
        image = add_dir(collection, material, dir, other_info={}, other_files=[], force=True)
        print('{ "_id" : "' + str(image) + '" }')
        images.append(image)
        energies.append(collection.find_one({'_id' : image}))
    ts_i = energies.index(max(energies))
    return collection.insert_one()
Exemple #8
0
def get_messages(email: str):
    global client
    try:
        db = client['users']
        collection = db['usersCollection']

        user_ob = collection.find_one({'email': email})
        user_id = str(user_ob['_id'])
        msg_db = client['msg']
        msg_collection = msg_db['msgCollection']
        messages = msg_collection.find_one({'user_id': user_id})
        return messages['messages_array']
    except Exception as e:
        print('Exception in get messages: ' + str(e))
Exemple #9
0
def login():
    get_email = request.form.get("email")
    get_password = request.form.get("password")
    login_cred = collection.find_one({"email": get_email})
    if login_cred:
        if login_cred['password'] == get_password:
            get_public_key = login_cred["public_key"]
            get_name = str(login_cred["name"])
            session["name"] = get_name
            session["public_key"] = get_public_key
            print("Succesful. E-mail: " + str(get_email))
            return redirect(url_for('showHomePage'))
        else:
            return jsonify({"error": "Login failed"}), 400
Exemple #10
0
def update(collection, query, object):
    existing = collection.find_one(query)
    col_name = collection.full_name
    obj_id = "FAIL"
    if existing:
        if existing.keys() == object.keys():
            obj_id = existing["_id"]
            log("%s: Not updated: " % col_name, obj_id)
        else:
            obj_id = collection.insert(object)
            log("%s: Updated object: " % col_name, obj_id)
    else:
        obj_id = collection.insert(object)
        log("%s: Inserted object: " % col_name, obj_id)

    return obj_id
Exemple #11
0
	def get_title(self, filename, password = None): 
		"""get the title of a note"""
		self.db = self.check_connection()
	
		notebookplusuid = self.helper.split_filename(filename)
		notebook = notebookplusuid[0]
		uid = notebookplusuid[1]
		collection = self.db[notebook]
		try: 
			title = collection.find_one({'_id' : uid })['title']
			if password:
                                title = encryption.decrypt_text(title, password)
		except TypeError: # a new note
			notedata = self.helper.add_note(collection, uid, password) 
			title = notedata[0]
		return str(title.encode('utf-8'))
def load_object(db_client: database.client.DatabaseClient, collection: pymongo.collection.Collection,
                id_: bson.ObjectId, **kwargs) -> typing.Union[None, database.entity.Entity]:
    """
    Shorthand helper for pulling a single entity from the database.
    This just saves us creating temporaries for serialized objects all the time,
    and wraps up a bunch of little checks so we don't have to repeat them.

    :param db_client: The database client, for deserializing the entity
    :param collection: The collection to load from
    :param id_: The id of the object to load
    :param kwargs: Additional keword arguments passed to deserialize, optional.
    :return: The deserialized object, or None if it doesn't exist
    """
    if db_client is None or collection is None or id_ is None:
        return None
    s_object = collection.find_one({'_id': id_})
    if s_object is not None:
        return db_client.deserialize_entity(s_object, **kwargs)
    return None
Exemple #13
0
def request_cancel(flight_id: str, date: datetime, email: str):
    global client
    try:

        user_db = client['users']
        user_collection = user_db['usersCollection']
        usr = user_collection.find_one({'email': email})
        cancel_db = client['cancels']

        collection = cancel_db['cancelsCollection']

        for each in usr['bookings']:
            if (each['flight_id'] == flight_id and each['date'] == date):

                item = {
                    'user_id': usr['_id'],
                    'flight_id': flight_id,
                    'e_count': each['e_count'],
                    'b_count': each['b_count'],
                    'date': date
                }

                d = datetime.date.today()

                x = int(date[len(date) - 2:])
                month = int(date[len(date) - 5:len(date) - 3])
                if (x - d.day < 2 and month == d.month):
                    return -2
                if (d.month != month and x >= 30 and d.day <= 2):
                    return -2

                if (collection.find(item).count() != 0):

                    return -1

                result = collection.insert_one(item)
                print('inserted into db',
                      collection.find_one({'flight_id': flight_id}))

                return 1

    except Exception as e:
        print('Exception in requesting cancel: ' + str(e))
def add_unique(collection: pymongo.collection.Collection, entity: database.entity.Entity) -> bson.ObjectId:
    """
    Add an object to a collection, if that object does not already exist.
    Treats the entire serialized object as the key, if only one entry is different, they're different objects.
    This ONLY works for very simple entities, more complex objects like image collections
    or image entities have their own save methods that check uniqueness.
    :param collection: The mongodb collection to insert into
    :param entity: The object to insert
    :return: The id of the entity, whether newly added or existing
    """
    if isinstance(entity, dict):
        s_object = entity
    else:
        s_object = entity.serialize()
    query = query_to_dot_notation(copy.deepcopy(s_object))
    existing = collection.find_one(query, {'_id': True})
    if existing is not None:
        return existing['_id']
    else:
        return collection.insert_one(s_object).inserted_id
Exemple #15
0
    def get_config_var(self, name):
        """DB에 저장된 환경값을 불러온다. 

        Args:
            name (str): 환경설정 변수명

        Raises:
            pymongo.erros.InvalidDocument: 잘못된 환경변수 이름
        """
        collection = self[self._db][COLLECTIONS['CONFIG']]

        my_query = {'variable': name}  # 검색필드
        my_result = {'value': True}  # 결과필드

        res = collection.find_one(my_query, my_result)

        if res is None:
            print(f"변수명 {name}이 존재하지 않습니다.")
            raise errors.InvalidDocument(f"환경설정({name})이 존재하지 않습니다.")
        return res['value']
Exemple #16
0
def signup():
    #get credentials
    set_name = request.form.get("name")
    set_email = request.form.get("email")
    set_password = request.form.get("password")

    #generate keypair
    alice = generate_keypair()
    public_key = alice.public_key
    private_key = alice.private_key

    #compile keypair and credentials into a list named "user"
    user_to_mongo = {
        "name": set_name,
        "email": set_email,
        "password": set_password,
        "public_key": public_key
    }

    #write user cred to a file.
    user_to_file = {
        "name": set_name,
        "email": set_email,
        "password": set_password,
        "public_key": public_key,
        "private_key": private_key
    }
    file_name = public_key + ".txt"
    with open(file_name, 'w') as file:
        file.write(json.dumps(user_to_file))
    file.close()

    #verify if the email already exist on the db
    if collection.find_one({"email": user_to_mongo['email']}):
        return jsonify({"error": "Email address already in use"}), 400

    #send "user" list to database
    collection.insert_one(user_to_mongo)
    flash("Account successfully created. Return to Login Page.")
    return send_file(file_name, as_attachment=True)
Exemple #17
0
def add_flight_to_db(request):
    global client
    try:
        route_id = request.form.get('route')
        b_seats = request.form.get('b_seats')
        e_seats = request.form.get('e_seats')
        d_time = request.form.get('d_time')
        a_time = request.form.get('a_time')
        f_id = request.form.get('f_id')
        db = client['route']
        collection = db['routeCollection']
        route = collection.find_one({'_id': ObjectId(route_id)})
        distance = int(route.get("distance"))
        b_cost = distance * 5
        e_cost = distance * 2
        flight_db = client['flight']
        flight_collection = flight_db['flightCollection']
        item = {
            'route_id': ObjectId(route_id),
            'b_seats': b_seats,
            'b_cost': b_cost,
            'e_seats': e_seats,
            'e_cost': e_cost,
            'f_id': f_id,
            'd_time': d_time,
            'a_time': a_time
        }
        result = flight_collection.insert_one(item)

        ticket_db = client['ticket']
        ticket_collection = ticket_db['ticketCollection']
        item = {'flight_id': result.inserted_id, 'tickets_array': {}}
        ticket_collection.insert_one(item)
        # print(item)
    except Exception as e:
        print("Error in add flight to db: " + str(e))
def find_guide(guide_number: str, collection: collection.Collection):
    return collection.find_one({"_id": guide_number})