def test_store_context(): path = tempfile.mkdtemp() store = FileSystemStore(path, 'http://localhost/') with raises(ContextError): get_current_store() with raises(ContextError): current_store.get_current_object() store2 = Store() with store_context(store) as s: assert s is store assert get_current_store() is store assert current_store == store with store_context(store2) as s2: assert s2 is store2 assert get_current_store() is store2 assert current_store == store2 with store_context(store) as s3: assert s3 is store assert get_current_store() is store assert current_store == store assert s2 is store2 assert get_current_store() is store2 assert current_store == store2 assert s is store assert get_current_store() is store assert current_store == store with raises(ContextError): get_current_store() with raises(ContextError): current_store.get_current_object() shutil.rmtree(path)
def newHobby(lizard_id): """newHobby: Displays new hobby creation form and posts new hobby to the database; requires login and that the logged-in user is also the user that created the lizard Arguments are derived from the url""" lizard = Lizard.query.filter_by(id=lizard_id).one() if request.method == "GET": with store_context(store): return render_template("newHobby.html", lizard=lizard, login_session=login_session) url = request.form.get("url") (url, error) = isURLImage(url) if error: return render_template("newHobby.html", login_session=login_session, lizard=lizard, error=error) try: url_open = urlopen(url) except: error = "Unable to make a request to this URL: %s" % (url) return render_template("newHobby.html", login_session=login_session, lizard=lizard, error=error) new_hobby = Hobby( name=request.form.get("name"), description=request.form.get("description"), lizard_id=lizard_id, user_id=lizard.user_id, picture_url=url) with store_context(store): new_hobby.picture.from_file(url_open) session.add(new_hobby) flash("New Hobby %s Successfully Created" % (new_hobby.name)) session.commit() url_open.close() newest_hobby = Hobby.query.\ filter_by(user_id=lizard.user_id).\ order_by(db.desc("creation_instant")).limit(1)[0] change_log = ChangeLog( user_id=lizard.user_id, lizard_name=lizard.name, lizard_id=lizard_id, hobby_name=newest_hobby.name, hobby_id=newest_hobby.id, update_instant=newest_hobby.creation_instant, action="new", table="hobby") session.add(change_log) session.commit() return redirect(url_for("showHobby", lizard_id=lizard_id))
def deleteLizard(lizard_id): """deleteLizard: Displays form to delete a lizard and posts that information to the database; requires login Arguments are derived from the url""" lizard_to_delete = Lizard.query.filter_by(id=lizard_id).one() if request.method == "GET": with store_context(store): return render_template( "deleteLizard.html", lizard=lizard_to_delete, login_session=login_session) change_log = ChangeLog( user_id=lizard_to_delete.user_id, lizard_name=lizard_to_delete.name, update_instant=datetime.datetime.utcnow(), action="delete", table="lizard") session.add(change_log) Hobby.query.filter_by(lizard_id=lizard_to_delete.id).delete() session.delete(lizard_to_delete) flash("Lizard %s Successfully Deleted" % lizard_to_delete.name) with store_context(store): session.commit() return redirect(url_for("showLizard"))
def deleteHobby(lizard_id, hobby_id): """deleteHobby: Displays form to delete an hobby and posts that information to the database; requires login and that the logged-in user is also the user that created the lizard Arguments are derived from the url""" lizard = Lizard.query.filter_by(id=lizard_id).one() hobby_to_delete = Hobby.query.\ filter_by(id=hobby_id, lizard_id=lizard_id).one() if request.method == "GET": with store_context(store): return render_template("deleteHobby.html", lizard=lizard, hobby=hobby_to_delete, login_session=login_session) change_log = ChangeLog( user_id=hobby_to_delete.user_id, lizard_name=lizard.name, lizard_id=lizard_id, hobby_name=hobby_to_delete.name, update_instant=datetime.datetime.utcnow(), action="delete", table="hobby") session.add(change_log) session.delete(hobby_to_delete) flash("Hobby %s Successfully Deleted" % (hobby_to_delete.name)) with store_context(store): session.commit() return redirect(url_for("showHobby", lizard_id=lizard_id))
def test_from_blob_implicitly(fx_session, tmp_store): with store_context(tmp_store): something = Something(name='some name') with open(os.path.join(sample_images_dir, 'iu.jpg'), 'rb') as f: expected = f.read() img = something.cover.from_blob(expected) assert something.cover.original is img with fx_session.begin(): fx_session.add(something) assert something.cover.original is img assert something.cover.count() == 1 assert img is something.cover.original with store_context(tmp_store): assert something.cover.make_blob() == expected
def test_from_blob_implicitly(fx_session, fx_sample_image, tmp_store): filepath, mimetype, (width, height) = fx_sample_image with store_context(tmp_store): something = Something(name='some name') with open(filepath, 'rb') as f: expected = f.read() img = something.cover.from_blob(expected) assert something.cover.original is img with fx_session.begin(): fx_session.add(something) assert something.cover.original is img assert something.cover.count() == 1 assert img is something.cover.original with store_context(tmp_store): assert something.cover.make_blob() == expected
def test_generate_thumbnail_implicitly(fx_session, fx_sample_image, tmp_store): filepath, mimetype, (width, height) = fx_sample_image with store_context(tmp_store): something = Something(name='some name') with raises(IOError): something.cover.generate_thumbnail(ratio=0.5) with open(filepath, 'rb') as f: original = something.cover.from_file(f) assert something.cover.original is original double = something.cover.generate_thumbnail(ratio=2) thumbnail = something.cover.generate_thumbnail(height=height // 2) assert something.cover \ .generate_thumbnail(width=width * 2) is double with fx_session.begin(): fx_session.add(something) assert something.cover.original is original assert something.cover.count() == 3 assert original is something.cover.original assert double.size == (width * 2, height * 2) assert thumbnail.height == height // 2 half_width = width // 2 # workaround off-by-one error assert thumbnail.width in (half_width - 1, half_width, half_width + 1) half_width = thumbnail.width assert something.cover \ .generate_thumbnail(width=half_width) is thumbnail with fx_session.begin(): x3 = something.cover.generate_thumbnail(width=width * 3) assert something.cover.count() == 4 x3.size == (width * 3, height * 3)
def test_delete_from_persistence(fx_session, tmp_store): with store_context(tmp_store): something = Something(name='some name') with open(os.path.join(sample_images_dir, 'iu.jpg'), 'rb') as f: image = something.cover.from_file(f) assert something.cover.original is image with fx_session.begin(): fx_session.add(something) assert something.cover.original is image args = ('samething-cover', image.object_id, image.width, image.height, image.mimetype) fx_session.execute('INSERT INTO samething ' 'SELECT * FROM something') fx_session.execute('INSERT INTO samething_cover ' 'SELECT * FROM something_cover') f.seek(0) tmp_store.put_file(f, *(args + (False,))) cover = fx_session.query(SamethingCover) \ .filter_by(samething_id=something.id) \ .one() with fx_session.begin(): fx_session.delete(cover) samething = fx_session.query(Samething).filter_by(id=something.id).one() assert samething.cover.original is None with raises(IOError): print(tmp_store.get_file(*args))
def editItem(item_id): if 'username' not in login_session: return redirect(url_for('showLogin')) item = session.query(Item).get(item_id) user_id = getUserID(login_session['email']) if item.user_id != user_id: response = make_response( json.dumps('You are not authorized to edit this item.'), 200) return response if request.method == 'POST': if request.form['item-name']: item.name = request.form['item-name'] if request.form['description']: item.description = request.form['description'] if request.files['item_photo']: try: with store_context(fs_store): item.picture.from_file(request.files['item_photo']) session.commit() except Exception: session.rollback() raise return redirect(url_for('showCategories')) else: categories = session.query(Category).order_by(asc(Category.name)) return render_template('edititem.html', categories=categories, item=item, login_session=login_session)
def showItem(item_id): item = session.query(Item).get(item_id) with store_context(fs_store): picture_url = item.picture.locate() user_id = getUserID(login_session['email']) return render_template('item.html', item=item, login_session=login_session, picture_url=picture_url, user_id=user_id)
def createItem(): if 'username' not in login_session: return redirect(url_for('showLogin')) if request.method == 'POST': category = session.query(Category).filter_by( name=request.form['item-category']).first() newItem = Item() newItem.name = request.form['item-name'] newItem.description = request.form['description'] newItem.category = category newItem.user_id = getUserID(login_session['email']) try: with store_context(fs_store): if request.files['item_photo']: newItem.picture.from_file(request.files['item_photo']) else: newItem.picture.from_file(urlopen(dummy_item_photo)) session.add(newItem) session.commit() except Exception: session.rollback() raise return redirect(url_for('showCategories')) else: categories = session.query(Category).order_by(asc(Category.name)) return render_template('create_item.html', categories=categories, login_session=login_session)
def post(self, *args, **kwargs): with store_context(store): message = self.db.query(Message).filter(Message.gid == kwargs.get('gid', 0)).first() if message is None: pass if message and message.id == message.thread.op().id: message.thread.deleted = True messages = self.db.query(Message).filter(Message.thread_id == message.thread_id).all() for mess in messages: mess.deleted = True if mess.picture: try: shutil.rmtree('%simages/%s' % (store.path, str(mess.id))) except: pass # Ну нет, так нет self.db.query(BoardImage).filter(BoardImage.message_gid == mess.id).delete() else: message.deleted = True if message.picture: try: shutil.rmtree('%simages/%s' % (store.path, str(message.id))) except: pass # Что тут поделаешь... self.db.query(BoardImage).filter(BoardImage.message_id == message.id).delete() self.db.commit() self.redirect(self.success_url)
def delete_square(self, square_id): with store_context(self.session_manager.fs_store): sess = self.session_manager.get_session() model = sess.query(Square).filter(Square.id == square_id).one() # self.delete_image(sess, model) sess.delete(model) sess.commit()
def fx_migration(fx_session, fx_source_store): with store_context(fx_source_store): with fx_session.begin(): a1 = Something(name='a1') fx_session.add(a1) with open(os.path.join(sample_images_dir, 'iu.jpg'), 'rb') as f: a1.cover.from_file(f) a1.cover.generate_thumbnail(height=480) a1.cover.generate_thumbnail(height=320) a1.cover.generate_thumbnail(height=160) a2 = Something(name='a2') fx_session.add(a2) with open(os.path.join(sample_images_dir, 'iu2.jpg'), 'rb') as f: a2.cover.from_file(f) b1 = Samething(name='b1') fx_session.add(b1) with open(os.path.join(sample_images_dir, 'asuka.jpg'), 'rb') as f: b1.cover.from_file(f) b1.cover.generate_thumbnail(height=375) b1.cover.generate_thumbnail(height=250) b1.cover.generate_thumbnail(height=125) b2 = Samething(name='b2') fx_session.add(b2) with open(os.path.join(sample_images_dir, 'shinji.jpg'), 'rb') as f: b2.cover.from_file(f)
def editLizard(lizard_id): """editLizard: Displays form to edit a lizard"s name and/or image url and posts that information to the database; requires login Arguments are derived from the url""" edited_lizard = Lizard.query.filter_by(id=lizard_id).one() if request.method == "GET": with store_context(store): return render_template("editLizard.html", lizard=edited_lizard, login_session=login_session) url = request.form.get("url") (url, error) = isURLImage(url) if error: return render_template("editLizard.html", login_session=login_session, lizard=edited_lizard, error=error) try: url_open = urlopen(url) except: error = "Unable to make a request to this URL: %s" % (url) return render_template("editLizard.html", login_session=login_session, lizard=edited_lizard, error=error) change_log = ChangeLog( user_id=edited_lizard.user_id, lizard_name=request.form.get("name"), lizard_id=lizard_id, update_instant=datetime.datetime.utcnow(), action="update", table="lizard") edited_lizard.name = request.form.get("name") edited_lizard.picture_url = url # Add all info to session while in store_context with store_context(store): edited_lizard.picture.from_file(url_open) session.add(change_log) session.add(edited_lizard) flash("Lizard %s Successfully Edited" % edited_lizard.name) session.commit() url_open.close() return redirect(url_for("showLizard"))
def test_from_raw_file_implicitly(fx_session, tmp_store): with store_context(tmp_store): something = Something(name='some name') with open(os.path.join(sample_images_dir, 'iu.jpg'), 'rb') as f: expected = f.read() f.seek(0) img = something.cover.from_raw_file(f, original=True) assert something.cover.original is img with fx_session.begin(): fx_session.add(something) assert something.cover.original is img assert something.cover.count() == 1 assert img is something.cover.original with store_context(tmp_store): with something.cover.open_file() as f: actual = f.read() assert actual == expected
def img_thumb(self): ''' миниатюра(по идее в настройках борды будут задаваться размеры) ''' with store_context(store): try: return self.picture.find_thumbnail(width=150).locate() except NoResultFound: return None
def test_from_raw_file_implicitly(fx_session, fx_sample_image, tmp_store): filepath, mimetype, (width, height) = fx_sample_image with store_context(tmp_store): something = Something(name='some name') with open(filepath, 'rb') as f: expected = f.read() f.seek(0) img = something.cover.from_raw_file(f, original=True) assert something.cover.original is img with fx_session.begin(): fx_session.add(something) assert something.cover.original is img assert something.cover.count() == 1 assert img is something.cover.original with store_context(tmp_store): with something.cover.open_file() as f: actual = f.read() assert actual == expected
def context_2(): try: s = get_current_store() except ContextError: values.append('error') else: values.append(s) with store_context(store_2): values.append(get_current_store())
def showLizard(): "showLizard: Displays all lizards; requires login" lizards = Lizard.query.order_by(db.asc(Lizard.name)).all() total_lizards = len(lizards) with store_context(store): return render_template("lizard.html", lizards=lizards, login_session=login_session, recent_activity=recentActivity(), pretty_date=pretty_date, total_lizards=total_lizards)
def create_image(self, tile_squares, width, height): with store_context(self.session_manager.fs_store): with Image(width=width * 25, height=height * 25) as image: image.format = 'jpeg' for tile_square in tile_squares: if tile_square.square is not None: with Image(file=tile_square.square.image) as square: image.composite(square.rotate(tile_square.rotation), tile_square.x_coordinate * 25, tile_square.y_coordinate * 25) return image.make_blob()
def set_logo(request, firm_id): try: firm = session.query(Firm).get(int(firm_id)) logo_url = request.values['picture'] image_binary = get(picture).content with store_context(store): firm.picture.from_blob(request.files[image_binary]) except Exception: session.rollback() raise session.commit()
def create_square(self, square): with store_context(self.session_manager.fs_store): sess = self.session_manager.get_session() if square.biome is not None: square.biome = sess.query(Biome).filter(Biome.id == square.biome.id).one() model = Square(width=square.width, height=square.height, image_type=square.image_type, square_type=square.square_type, biome=square.biome) # , tiles=square.tiles) if square.image is not None: model.image.from_blob(self.resize_image(square.image, square.width, square.height)) sess.add(model) sess.commit() return model
def image_info(self): ''' Полноразмерное изображение ''' with store_context(store): locate = self.picture.locate() return { 'locate': locate, 'name': locate.split('/')[-1].split('?')[0], 'width': self.picture.original.width, 'height': self.picture.original.height }
def showPublicLizard(): """showPublicLizard: Displays lizards, does not require login Routes: "/" "/publicLizard/""""" lizards = Lizard.query.order_by(db.asc(Lizard.name)).all() total_lizards = len(lizards) with store_context(store): return render_template("publicLizard.html", lizards=lizards, recent_activity=recentActivity(), pretty_date=pretty_date, total_lizards=total_lizards)
def get_picture_url(dbtype, item_id): """Redirect stored image url within the db to an organized url for Antibody/Cytotoxin/Adc.html to access """ item = session.query(eval(dbtype.capitalize())).filter_by(id=item_id).one() with store_context(fs_store): try: picture_url = item.picture.locate() except IOError: print "No picture found for lot# %s" % str(item_id) picture_url = '' return render_template('img.html', item=item, picture_url=picture_url, dbtype=dbtype)
def newLizard(): """newLizard: Displays new lizard creation form and posts new lizard to the database; requires login""" if request.method == "GET": return render_template("newLizard.html", login_session=login_session) # First check to see if image URL is valid from HEAD reqauest. # If its not return error url = request.form.get("url") (url, error) = isURLImage(url) if error: return render_template("newLizard.html", login_session=login_session, error=error) # urlopen uses a GET request and does not accept HTTPS urls try: url_open = urlopen(url) except: error = "Unable to make a request to this URL: %s" % (url) return render_template("newLizard.html", login_session=login_session, error=error) # Create Lizard object new_lizard = Lizard( name=request.form.get("name"), user_id=login_session.get("user_id"), picture_url=url) # Must add picture to lizard object within store_context with store_context(store): new_lizard.picture.from_file(url_open) # adding picture here session.add(new_lizard) session.commit() url_open.close() # make sure to close url connection after commit # After commit, retrieve lizard info to add to the ChangeLog newest_lizard = Lizard.query.\ filter_by(user_id=login_session.get("user_id")).\ order_by(db.desc("creation_instant")).limit(1)[0] change_log = ChangeLog( user_id=newest_lizard.user_id, lizard_name=newest_lizard.name, lizard_id=newest_lizard.id, update_instant=newest_lizard.creation_instant, action="new", table="lizard") session.add(change_log) flash("New Lizard %s Successfully Created" %\ (newest_lizard.name)) session.commit() return redirect(url_for("showLizard"))
def showHobby(lizard_id): """showHobby: Displays all hobbies of a particular lizard; requires login and that the logged-in user is also the user that created the lizard Args: lizard_id: : ID of the lizard being edited""" lizard = Lizard.query.filter_by(id=lizard_id).one() hobbies = Hobby.query.filter_by(lizard_id=lizard_id).all() creator = User.query.filter_by(id=lizard.user_id).one() with store_context(store): return render_template( "hobby.html", hobbies=hobbies, lizard=lizard, login_session=login_session, creator=creator, user_id=login_session["user_id"])
def test_delete(fx_session, tmp_store): with store_context(tmp_store): something = Something(name='some name') with open(os.path.join(sample_images_dir, 'iu.jpg'), 'rb') as f: image = something.cover.from_file(f) assert something.cover.original is image with fx_session.begin(): fx_session.add(something) assert something.cover.original is image args = (image.object_type, image.object_id, image.width, image.height, image.mimetype) with fx_session.begin(): fx_session.delete(image) assert something.cover.original is None with raises(IOError): tmp_store.get_file(*args)
def edit_square(self, square): with store_context(self.session_manager.fs_store): sess = self.session_manager.get_session() model = sess.query(Square).filter(Square.id == square.id).one() model.width = square.width model.height = square.height model.image_type = square.image_type model.square_type = square.square_type if square.biome is not None: model.biome = sess.query(Biome).filter(Biome.id == square.biome.id).one() if square.image is not None: model.image.from_blob(self.resize_image(square.image, square.width, square.height)) else: sess.delete(model.image[0]) sess.commit() return model