def teardown(self): # Close the session. self._db.close() # Roll back all database changes that happened during this # test, whether in the session that was just closed or some # other session. self.transaction.rollback() # Remove any database objects cached in the model classes but # associated with the now-rolled-back session. Collection.reset_cache() ConfigurationSetting.reset_cache() DataSource.reset_cache() DeliveryMechanism.reset_cache() ExternalIntegration.reset_cache() Genre.reset_cache() Library.reset_cache() # Also roll back any record of those changes in the # Configuration instance. for key in [ Configuration.SITE_CONFIGURATION_LAST_UPDATE, Configuration.LAST_CHECKED_FOR_SITE_CONFIGURATION_UPDATE ]: if key in Configuration.instance: del (Configuration.instance[key]) if self.search_mock: self.search_mock.stop()
def teardown(self): # Close the session. self._db.close() # Roll back all database changes that happened during this # test, whether in the session that was just closed or some # other session. self.transaction.rollback() # Remove any database objects cached in the model classes but # associated with the now-rolled-back session. Collection.reset_cache() ConfigurationSetting.reset_cache() DataSource.reset_cache() DeliveryMechanism.reset_cache() ExternalIntegration.reset_cache() Genre.reset_cache() Library.reset_cache() # Also roll back any record of those changes in the # Configuration instance. for key in [ Configuration.SITE_CONFIGURATION_LAST_UPDATE, Configuration.LAST_CHECKED_FOR_SITE_CONFIGURATION_UPDATE ]: if key in Configuration.instance: del(Configuration.instance[key]) if self.search_mock: self.search_mock.stop()
def all(cls, _db, **constructor_kwargs): """Yield a sequence of CollectionMonitor objects: one for every Collection associated with cls.PROTOCOL. Monitors that have no Timestamp will be yielded first. After that, Monitors with older Timestamps will be yielded before Monitors with newer timestamps. :param constructor_kwargs: These keyword arguments will be passed into the CollectionMonitor constructor. """ service_match = or_(Timestamp.service==cls.SERVICE_NAME, Timestamp.service==None) collections = Collection.by_protocol(_db, cls.PROTOCOL).outerjoin( Timestamp, and_( Timestamp.collection_id==Collection.id, service_match, ) ) collections = collections.order_by( Timestamp.timestamp.asc().nullsfirst() ) for collection in collections: yield cls(_db=_db, collection=collection, **constructor_kwargs)
def add_collection(user, auth): user = get_user_by_name(session, user) if not user: return error_user_not_found() if not is_user_logged_in(session, auth, user.display_name): return error_request_denied() body = bottle.request.json name_missing = "name" not in body description_missing = "description" not in body if name_missing or description_missing: bottle.response.status = 400 return {"error": "Missing required parameters."} name = body["name"] description = body["description"] already_exists = get_collection_by_name(session, name) if already_exists: bottle.response.status = 400 return {"error": "There is already a collection with that name."} new_collection = Collection(user=user, name=name, description=description) session.add(new_collection) session.commit() return {"id": new_collection.id}
def add_new(self, name, type): new_collection = Collection(name=name, type=type) db_session.add(new_collection) db_session.commit() return new_collection
def all(cls, _db, **constructor_kwargs): """Yield a sequence of CollectionMonitor objects: one for every Collection associated with cls.PROTOCOL. Monitors that have no Timestamp will be yielded first. After that, Monitors with older values for Timestamp.start will be yielded before Monitors with newer values. :param constructor_kwargs: These keyword arguments will be passed into the CollectionMonitor constructor. """ service_match = or_(Timestamp.service==cls.SERVICE_NAME, Timestamp.service==None) collections = Collection.by_protocol(_db, cls.PROTOCOL).outerjoin( Timestamp, and_( Timestamp.collection_id==Collection.id, service_match, ) ) collections = collections.order_by( Timestamp.start.asc().nullsfirst() ) for collection in collections: yield cls(_db=_db, collection=collection, **constructor_kwargs)
def setUp(self): DB.drop_all() DB.create_all() collect = Collection('1', 'National Museum of Art', 'http://www.nga.gov', 'North America', 'Institution') DB.session.add(collect) DB.session.commit()
def create_collection(user_collection, name): """Creates a collection of podcasts for a user.""" collect = Collection(user_collection=user_collection, name=name) db.session.add(collect) db.session.commit() return collect
def create_collection(user, collection_type, lendable=False, private=False): collection = Collection(user=user, collection_type=collection_type, lendable=lendable, private=private) db.session.add(collection) db.session.commit() return collection
def create_collection(id): form = forms.NewCollectionForm(request.form) if not form.validate(): flash("Error, all fields are required") else: collection = Collection(title=form.title.data, description=form.description.data, user_id=current_user.id) model.session.add(collection) model.session.commit() return redirect(url_for("view_user", id=current_user.id))
def create_collection(user_id, notes, date_saved=datetime.today()): """Create and return a new collection.""" new_collection = Collection(user_id=user_id, notes=notes, date_saved=date_saved) db.session.add(new_collection) db.session.commit() return new_collection
def test_addition_deletion(self): """ Test adding and deleting """ collect = Collection('2', 'Kimbell Museum of Art', 'https://www.kimbellart.org', 'North America', 'Institution') DB.session.add(collect) DB.session.commit() self.assertEqual(len(Collection.query.all()), 2) Collection.query.filter_by( institution='Kimbell Museum of Art').delete() DB.session.commit() self.assertEqual(len(Collection.query.all()), 1)
def pet_star(): info = {'result': 0, 'msg': "成功", 'data': None} json_data = json.loads(request.get_data()) phone = json_data['phone'] pet_code = json_data['PetCode'] star = json_data['star'] if star is True: c = Collection(phone=phone, pet_code=pet_code) db.session.add(c) db.session.commit() elif star is False: c = Collection(phone=phone, pet_code=pet_code) db.session.delete(c) db.session.commit() else: info['result'] = 1 info['msg'] = '失败' info['data'] = '操作失败' return jsonify(info)
def preload_tables(self, db): base_path = os.path.split(__file__)[0] #self.resource_path = os.path.join(base_path, "files", "oneclick") path = os.path.join(base_path, "example.json") data = open(path).read() dict_data = json.loads(data) collections = dict_data['collections'] coll_1 = Collection() coll_1.name = collections[0]['name'] coll_1.curator = collections[0]['curator'] display_items = collections[0]['display_items'] db.commit() print "hi"
def to_collection(self, _db): """Find or create a Collection object for this Overdrive Advantage account. :return: a 2-tuple of Collections (primary Overdrive collection, Overdrive Advantage collection) """ # First find the parent Collection. try: parent = Collection.by_protocol(_db, ExternalIntegration.OVERDRIVE).filter( Collection.external_account_id==self.parent_library_id ).one() except NoResultFound, e: # Without the parent's credentials we can't access the child. raise ValueError( "Cannot create a Collection whose parent does not already exist." )
def upload(): """ DOCS: http://zabana.me/notes/upload-files-amazon-s3-flask.html """ files = request.files.getlist('user_file') user = User.query.filter(User.username == session['username']).first() # Check if there's a 'user_file' key if len(files) == 0: flash('No files were selected. Please select file(s) to upload.') return redirect('/new_collection') # Create a new collection instance and commit to database uuid_string = str(uuid.uuid4()) new_collection = Collection(user=user, uuid=uuid_string) db.session.add(new_collection) db.session.commit() # Upload photos to s3 try: upload_files(files, new_collection.id) except: flash('Failed to upload files. Please try again. ') return redirect('/new_collection') # Faces indexing and matching if create_rekognition_collection(new_collection.id) == True: try: for photo in new_collection.photos: index_faces(new_collection.id, photo.s3_key, photo.id) process_faces(new_collection.id) except: flash('Failed to process files. Please try again. ') return redirect('/new_collection') # Update the database with the time finish processing the collection new_collection.time_processed = datetime.utcnow() db.session.commit() flash('Your collection of pictures was processed successfully!') # Delete the collection when it's done delete_rekognition_collection(new_collection.id) return redirect(f'/collections/{new_collection.id}')
def all(cls, _db, **kwargs): """Yield a sequence of CollectionCoverageProvider instances, one for every Collection that gets its licenses from cls.PROTOCOL. CollectionCoverageProviders will be yielded in a random order. :param kwargs: Keyword arguments passed into the constructor for CollectionCoverageProvider (or, more likely, one of its subclasses). """ if cls.PROTOCOL: collections = Collection.by_protocol(_db, cls.PROTOCOL) else: collections = _db.query(Collection) collections = collections.order_by(func.random()) for collection in collections: yield cls(collection, **kwargs)
def createCollection(self, title, creator, description, owner, workUUIDs=[], editionIDs=[]): newCollection = Collection(uuid=uuid4(), title=title, creator=creator, description=description, owner=owner) collectionEditions = [] if len(workUUIDs) > 0: collectionWorks = self.session.query(Work)\ .join(Work.editions)\ .filter(Work.uuid.in_(workUUIDs))\ .all() for work in collectionWorks: editions = list( sorted([ed for ed in work.editions], key=lambda x: x.publication_date if x.publication_date else date.today())) for edition in editions: if len(edition.items) > 0: collectionEditions.append(edition) break if len(editionIDs) > 0: collectionEditions.extend( self.session.query(Edition).filter( Edition.id.in_(editionIDs)).all()) newCollection.editions = collectionEditions self.session.add(newCollection) return newCollection
def add_new_collection(): """Add a new collection to user from profile.""" user_email = session['email'] user = User.query.filter_by(email=user_email).first() new_title = request.form['title'] existing_collection = Collection.query.filter_by(title=new_title, user_id=user.id).first() if existing_collection == None: new_collection = Collection(title=new_title, user_id=user.id) db.session.add(new_collection) db.session.commit() flash('Successfully added new collection: %s' % new_collection.title) return redirect('/profile') else: flash('Collection with this title already exists') return redirect('/profile')
def load_collections(): print "Adding User Collections" user_id = User.query.filter_by( email=os.environ['SAMPLE_EMAIL']).first().user_id with open('data/recipe_files/past_meals.csv') as file: for line in file: line = line.rstrip().split(',') col_data = Collection(user_id=user_id, assigned_date=line[2].lstrip().rstrip(), set_number=line[3].lstrip().rstrip(), set_day=line[4].lstrip().rstrip(), meal_type=line[5].lstrip().rstrip(), recipe_id=line[6].lstrip().rstrip()) db.session.add(col_data) db.session.commit()
def collection(self): return Collection.by_id(self._db, id=self.collection_id)
def display_current_meal_plan(): """ If no meal plan currently exists, creates one. If meal plan already exits, displays the current week's meal plan Collection attribute 'set_number' is a concat of current year, week of year, i.e. YYYYWW Collection attribute 'set_day' is a single digit indicating the number of the day of the week to which it corresponds, i.e. 1 == Monday, 2 == Tuesday, etc. """ week = datetime.date.today().strftime("%W") thisweek = Week.thisweek().week year = datetime.date.today().strftime("%Y") start_date = datetime.datetime.strptime(year + "-W" + str(thisweek) + "-1", "%Y-W%W-%w") start_day = start_date.strftime("%b %d, %Y") set_number = year + week user_id = session['user_id'] # If Collection does not already exist for the current week, create one if len( Collection.query.filter(Collection.set_number == set_number, Collection.user_id == user_id).all()) == 0: user_prefs = [] prefs = db.session.query(UserPreference.category_id).filter( UserPreference.user_id == user_id).all() for pref in prefs: user_prefs.append(pref[0]) if len(user_prefs) > 0: breakfast = Category.query.filter( Category.category_name.in_(breakfast_list)).all() lunch = Category.query.filter( Category.category_id.in_(user_prefs)).all() dinner = Category.query.filter( Category.category_id.in_(user_prefs)).all() else: breakfast = Category.query.filter( Category.category_name.in_(breakfast_list)).all() lunch = Category.query.filter( Category.category_name.in_(lunch_list)).all() dinner = Category.query.filter( Category.category_name.in_(dinner_list)).all() weekly_breakfasts = meal_plan.make_meal_set(breakfast, user_prefs) weekly_lunches = meal_plan.make_meal_set(lunch, user_prefs) weekly_dinners = meal_plan.make_meal_set(dinner, user_prefs) # Create Collection object from this week's selected breakfast recipes day_num = 0 for item in weekly_breakfasts: day_num += 1 breakfast_recipe = Collection(user_id=session['user_id'], assigned_date=start_day, set_number=set_number, set_day=day_num, meal_type="breakfast", recipe_id=item.recipe_id) db.session.add(breakfast_recipe) # Create Collection object from this week's selected lunch recipes day_num = 0 for item in weekly_lunches: day_num += 1 lunch_recipe = Collection(user_id=session['user_id'], assigned_date=start_day, set_number=set_number, set_day=day_num, meal_type="lunch", recipe_id=item.recipe_id) db.session.add(lunch_recipe) # Create Collection object from this week's selected dinner recipes day_num = 0 for item in weekly_dinners: day_num += 1 dinner_recipe = Collection(user_id=session['user_id'], assigned_date=start_day, set_number=set_number, set_day=day_num, meal_type="dinner", recipe_id=item.recipe_id) db.session.add(dinner_recipe) db.session.commit() # Pull this week's Collection objects to pass into the HTML template & # render in the meal plan page breakfasts = Collection.query.filter( Collection.user_id == user_id, Collection.set_number == set_number, Collection.meal_type == "breakfast").order_by( Collection.set_day).all() lunches = Collection.query.filter( Collection.user_id == user_id, Collection.set_number == set_number, Collection.meal_type == "lunch").order_by( Collection.set_day).all() dinners = Collection.query.filter( Collection.user_id == user_id, Collection.set_number == set_number, Collection.meal_type == "dinner").order_by( Collection.set_day).all() # Get shopping list using Ingredients module final_ingredients = ingredients.get_shopping_list( breakfasts, lunches, dinners) return render_template("meal_plan.html", now=week, breakfasts=breakfasts, lunches=lunches, dinners=dinners, ingredients=final_ingredients, start_day=start_day) # If Collection objects already exist for this week's meal plan, query them # and return them with the HTML template else: breakfasts = Collection.query.filter( Collection.user_id == user_id, Collection.set_number == set_number, Collection.meal_type == "breakfast").order_by( Collection.set_day).all() lunches = Collection.query.filter( Collection.user_id == user_id, Collection.set_number == set_number, Collection.meal_type == "lunch").order_by( Collection.set_day).all() dinners = Collection.query.filter( Collection.user_id == user_id, Collection.set_number == set_number, Collection.meal_type == "dinner").order_by( Collection.set_day).all() # Generate shopping list using Ingredients module final_ingredients = ingredients.get_shopping_list( breakfasts, lunches, dinners) return render_template("meal_plan.html", now=week, breakfasts=breakfasts, lunches=lunches, dinners=dinners, ingredients=final_ingredients, start_day=start_day)
display_name='Paul Bob', password_hash=bcrypt.hashpw('PaulPass'.encode(), bcrypt.gensalt()))) session.add( User(email='*****@*****.**', display_name='John Bob', password_hash=bcrypt.hashpw('JohnPass'.encode(), bcrypt.gensalt()))) RueBob = User(email='*****@*****.**', display_name='Rue Bob', password_hash=bcrypt.hashpw('RuePass'.encode(), bcrypt.gensalt())) session.add(RueBob) fossil_collection = Collection(user=RueBob, name="Fossils", description="Some fossils") butterfly_collection = Collection(user=RueBob, name="Butterflies", description="Some butterflies") session.add(butterfly_collection) session.add(fossil_collection) fossil = Item(collection=fossil_collection, name="A fossil", description="A fossil for the collection") session.add(fossil) butterfly = Item(collection=butterfly_collection,