def create(cls, gc, session_key='session.key', dsn='sqlite://', name=None, base=None, store_root=None, store_prefix=None): if name is None: name = str(cls.__name__.lower()) # We register our SQLengine under a given name engine = create_engine(dsn, name) # We use a declarative base, if it exists we bind it and create if base is not None: engine.bind(base) metadata = base.metadata metadata.create_all(engine.engine, checkfirst=True) if store_root is not None: fs_store = HttpExposedFileSystemStore(store_root, store_prefix) else: fs_store = None # Configuration object factory = namedtuple('Configuration', ('session_key', 'engine', 'name', 'fs_store')) configuration = factory(session_key, engine, name, fs_store) if cls.check_configuration is not None: errors = [] for iface in cls.check_configuration: errors.extends(getValidationErrors(iface, configuration)) if errors: raise RuntimeError('Errors occured: %s' % ', '.join(errors)) app = cls(configuration) if store_root is not None: return fs_store.wsgi_middleware(app) return app
def test_http_fs_store(tmpdir, **kwargs): http_fs_store = HttpExposedFileSystemStore(tmpdir.strpath, **kwargs) image = TestingImage(thing_id=1234, width=405, height=640, mimetype='image/jpeg', original=True, created_at=utcnow()) image_path = os.path.join(sample_images_dir, 'iu.jpg') with open(image_path, 'rb') as image_file: expected_data = image_file.read() image_file.seek(0) http_fs_store.store(image, image_file) with http_fs_store.open(image) as actual: actual_data = actual.read() assert expected_data == actual_data expected_urls = ( 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpe', 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpg' ) return http_fs_store, image, expected_data, expected_urls
def create_app(config): """Creates flask application with configuration """ app = App(__name__) # Configure application app.config.setdefault('DATABASE', 'db.db') if isinstance(config, collections.Mapping): app.config.update(config) else: app.config.from_object(config) # View registering views.register_views(app) # DB connection app.db_engine = create_engine(app.config['DATABASE']) m.Base.metadata.bind = app.db_engine m.Session.configure(bind=app.db_engine) # Image Store app.store = HttpExposedFileSystemStore('images', 'images/') app.wsgi_app = app.store.wsgi_middleware(app.wsgi_app) @app.before_request def store_before_request(): context.push_store_context(app.store) @app.teardown_request def store_teardown_request(exception=None): context.pop_store_context() # Auth app.register_blueprint(auth_blueprint) @app.before_request def before_request(): g.user = get_login_user() # Middlewares SQLAlchemyMiddleware(m.Session, app) # Admin def get_session(): session = getattr(self, '_session', None) if (session is None) or not session.is_active: session = m.Session() setattr(self, '_session', session) return session session = Proxy(get_session) admin = Admin(app) admin.add_view(ModelView(m.Issue, session, category='models')) admin.add_view(ModelView(m.User, session, category='models')) return app
def test_http_fs_store(tmpdir, **kwargs): http_fs_store = HttpExposedFileSystemStore(tmpdir.strpath, **kwargs) image = TestingImage(thing_id=1234, width=405, height=640, mimetype='image/jpeg', original=True, created_at=utcnow()) image_path = os.path.join(sample_images_dir, 'iu.jpg') with open(image_path, 'rb') as image_file: expected_data = image_file.read() image_file.seek(0) http_fs_store.store(image, image_file) with http_fs_store.open(image) as actual: actual_data = actual.read() assert expected_data == actual_data expected_urls = ( 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpe', 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpg') return http_fs_store, image, expected_data, expected_urls
def test_http_fs_store(tmpdir): http_fs_store = HttpExposedFileSystemStore(tmpdir.strpath) image = TestingImage(thing_id=1234, width=405, height=640, mimetype='image/jpeg', original=True, created_at=utcnow()) image_path = os.path.join(sample_images_dir, 'iu.jpg') with open(image_path, 'rb') as image_file: expected_data = image_file.read() image_file.seek(0) http_fs_store.store(image, image_file) with http_fs_store.open(image) as actual: actual_data = actual.read() assert expected_data == actual_data expected_urls = ( 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpe', 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpg') def app(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain; charset=utf-8')]) yield http_fs_store.locate(image).encode('utf-8') app = http_fs_store.wsgi_middleware(app) request = Request.blank('/') response = request.get_response(app) actual_url = response.text assert remove_query(actual_url) in expected_urls request = Request.blank('/__images__/testing/234/1/1234.405x640.jpe') response = request.get_response(app) assert response.status_code == 200 assert response.body == expected_data assert response.content_type == 'image/jpeg' http_fs_store.delete(image) with raises(IOError): http_fs_store.open(image) tmpdir.remove()
def test_http_fs_store(tmpdir): http_fs_store = HttpExposedFileSystemStore(tmpdir.strpath) image = TestingImage(thing_id=1234, width=405, height=640, mimetype='image/jpeg', original=True, created_at=utcnow()) image_path = os.path.join(sample_images_dir, 'iu.jpg') with open(image_path, 'rb') as image_file: expected_data = image_file.read() image_file.seek(0) http_fs_store.store(image, image_file) with http_fs_store.open(image) as actual: actual_data = actual.read() assert expected_data == actual_data expected_urls = ( 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpe', 'http://localhost:80/__images__/testing/234/1/1234.405x640.jpg' ) def app(environ, start_response): start_response( '200 OK', [('Content-Type', 'text/plain; charset=utf-8')] ) yield http_fs_store.locate(image).encode('utf-8') app = http_fs_store.wsgi_middleware(app) request = Request.blank('/') response = request.get_response(app) actual_url = response.text assert remove_query(actual_url) in expected_urls request = Request.blank('/__images__/testing/234/1/1234.405x640.jpe') response = request.get_response(app) assert response.status_code == 200 assert response.body == expected_data assert response.content_type == 'image/jpeg' http_fs_store.delete(image) with raises(IOError): http_fs_store.open(image) tmpdir.remove()
import sys app = Flask(__name__) csrf = SeaSurf(app) # Connect to Database and create database session BASE_DIR = os.path.dirname(os.path.abspath(__file__)) engine = create_engine('postgresql://*****:*****@localhost/itemscatalog') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # session = DBSession() Session = scoped_session(DBSession) session = Session() # for images uploading fs_store = HttpExposedFileSystemStore('/tmp/itemimages', 'images/') app.wsgi_app = fs_store.wsgi_middleware(app.wsgi_app) dummy_item_photo = '''http://www.canadacontestsonline.com /wp-content/themes/Wordie/images/no_image.png''' CLIENT_ID = json.loads( open(os.path.join(BASE_DIR, 'client_secrets.json'), 'r').read())['web']['client_id'] APPLICATION_NAME = "Item Catalog" # Create anti-forgery state token @app.route('/login') def showLogin(): state = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32))
import json import os from sqlalchemy_imageattach.stores.fs import HttpExposedFileSystemStore # Allowed Extensions for Uploaded Pictures ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'bmp']) # absolute path of the app on server app_path = '/vagrant/' # variables and path for postgres database user = '******' password = '******' db_name = 'biologics-catalog' db_path = 'postgresql://{0}:{1}@localhost/{2}'.format(user, password, db_name) # Location of where the pictures will be uploaded and their web url fs_store = HttpExposedFileSystemStore( path=os.path.join(app_path, 'static/images/')) # Google OAuth Objects google_client_secrets = json.loads( open(os.path.join(app_path, 'client_secrets.json'), 'r').read()) # Facebook OAuth Objects facebook_client_secrets = json.loads( open(os.path.join(app_path, 'fb_client_secrets.json'), 'r').read())
import sys import json import os # First check if user passed in a valid integer try: user_id = int(sys.argv[1]) except: raise ValueError("User must pass in a valid integer") # Next check that the user_id actually exists try: user = User.query.filter_by(id=user_id).one() except: raise ValueError("User must pass in a valid user id") store = HttpExposedFileSystemStore( path=os.path.join(os.path.dirname(__file__), "pkg/images")) app.wsgi_app = store.wsgi_middleware(app.wsgi_app) with open("testData.JSON") as data_file: lizards = json.load(data_file) for next_lizard in lizards["lizards"]: lizard = Lizard(name=next_lizard["name"], user_id=user_id, picture_url=next_lizard["picture_url"]) (url, error) = isURLImage(next_lizard["picture_url"]) if not error: url_open = urlopen(url) with store_context(store): lizard.picture.from_file(url_open) session.add(lizard)
from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from sqlalchemy_imageattach.stores.fs import HttpExposedFileSystemStore app = Flask(__name__) store = HttpExposedFileSystemStore( path='tmp/images', prefix='static/images/' ) app.wsgi_app = store.wsgi_middleware(app.wsgi_app) CORS(app) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database/app.db' db = SQLAlchemy(app) from engine import routes
import sys app = Flask(__name__) csrf = SeaSurf(app) # Connect to Database and create database session BASE_DIR = os.path.dirname(os.path.abspath(__file__)) engine = create_engine('postgresql://*****:*****@localhost/itemscatalog') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) # session = DBSession() Session = scoped_session(DBSession) session = Session() # for images uploading fs_store = HttpExposedFileSystemStore('/tmp/itemimages', 'images/') app.wsgi_app = fs_store.wsgi_middleware(app.wsgi_app) dummy_item_photo = '''http://www.canadacontestsonline.com /wp-content/themes/Wordie/images/no_image.png''' CLIENT_ID = json.loads( open(os.path.join(BASE_DIR, 'client_secrets.json'), 'r').read())['web']['client_id'] APPLICATION_NAME = "Item Catalog" # Create anti-forgery state token @app.route('/login') def showLogin(): state = ''.join(
def get_store(cls): store = HttpExposedFileSystemStore('store', 'images') return store
from flask import Flask from flask_sqlalchemy import SQLAlchemy from sqlalchemy_imageattach.stores.fs import HttpExposedFileSystemStore import config app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) image_store = HttpExposedFileSystemStore(path=config.IMAGE_STORE_PATH, prefix=config.IMAGE_STORE_PREFIX) app.wsgi_app = image_store.wsgi_middleware(app.wsgi_app) # noinspection PyUnresolvedReferences from flaskbook.orm import models # noinspection PyUnresolvedReferences from flaskbook.ui import views