def initialize(settings, options): engine = engine_from_config(settings, 'sqlalchemy.') config = Configurator(settings=settings) pyramid_dogpile_cache.includeme(config) from gengine.metadata import (init_session, init_declarative_base, init_db) init_caches() init_session() init_declarative_base() init_db(engine) from gengine.metadata import (Base, DBSession) if options.get("reset_db", False): Base.metadata.drop_all(engine) engine.execute("DROP SCHEMA IF EXISTS public CASCADE") engine.execute("CREATE SCHEMA IF NOT EXISTS public") from alembic.config import Config from alembic import command from alembic.runtime.migration import MigrationContext alembic_cfg = Config(attributes={'engine': engine, 'schema': 'public'}) script_location = os.path.join( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'app/alembic') alembic_cfg.set_main_option("script_location", script_location) context = MigrationContext.configure(engine.connect()) current_rev = context.get_current_revision() if not current_rev: #init from gengine.app import model tables = [ t for name, t in model.__dict__.items() if isinstance(t, Table) ] Base.metadata.create_all(engine, tables=tables) command.stamp(alembic_cfg, "head") if options.get("populate_demo", False): populate_demo(DBSession) admin_user = options.get("admin_user", False) admin_password = options.get("admin_password", False) if admin_user and admin_password: create_user(DBSession=DBSession, user=admin_user, password=admin_password) else: #upgrade command.upgrade(alembic_cfg, 'head') engine.dispose()
def main(argv=sys.argv): if len(argv) < 2: usage(argv) config_uri = argv[1] options = parse_vars(argv[2:]) setup_logging(config_uri) settings = get_appsettings(config_uri, options=options) from gengine.base.settings import set_settings set_settings(settings) durl = os.environ.get("DATABASE_URL") # heroku if durl: settings['sqlalchemy.url'] = durl murl = os.environ.get("MEMCACHED_URL") if murl: settings['urlcache_url'] = murl engine = engine_from_config(settings, 'sqlalchemy.') config = Configurator(settings=settings) pyramid_dogpile_cache.includeme(config) from gengine.metadata import ( init_session, init_declarative_base, init_db ) init_session() init_declarative_base() init_db(engine) init_caches() from gengine.metadata import ( DBSession ) sess = DBSession() init_session(override_session=sess, replace=True) import gengine.app.model as m with transaction.manager: mark_changed(sess, transaction.manager, True) messages = sess.execute(m.t_user_messages.select().where(m.t_user_messages.c.has_been_pushed == False)) for msg in messages: m.UserMessage.deliver(msg) sess.flush() sess.commit()
def revision(settings, message, options): engine = engine_from_config(settings, 'sqlalchemy.') config = Configurator(settings=settings) pyramid_dogpile_cache.includeme(config) from gengine.metadata import (init_session, init_declarative_base, init_db) init_session() init_declarative_base() init_db(engine) from gengine.app.cache import init_caches init_caches() from gengine.metadata import ( Base, ) if options.get("reset_db", False): Base.metadata.drop_all(engine) engine.execute("DROP SCHEMA IF EXISTS public CASCADE") engine.execute("CREATE SCHEMA IF NOT EXISTS public") from alembic.config import Config from alembic import command alembic_cfg = Config(attributes={'engine': engine, 'schema': 'public'}) script_location = os.path.join( os.path.dirname( os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'app/alembic') alembic_cfg.set_main_option("script_location", script_location) command.revision(alembic_cfg, message, True) engine.dispose()
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ durl = os.environ.get("DATABASE_URL") #heroku if durl: settings['sqlalchemy.url']=durl murl = os.environ.get("MEMCACHED_URL") #heroku if murl: settings['urlcache_url']=murl set_settings(settings) print("settings ",settings) engine = engine_from_config(settings, 'sqlalchemy.', connect_args={"options": "-c timezone=utc"}, ) config = Configurator(settings=settings) from gengine.app.cache import init_caches init_caches() from gengine.metadata import init_session, init_declarative_base, init_db init_session() init_declarative_base() init_db(engine) from gengine.base.monkeypatch_flaskadmin import do_monkeypatch do_monkeypatch() def reset_context_on_new_request(event): reset_context() config.add_subscriber(reset_context_on_new_request,NewRequest) config.include('pyramid_dogpile_cache') config.include("pyramid_tm") config.include('pyramid_chameleon') config.include('pyramid_jinja2') config.add_static_view(name='static', path='gengine.app:static') urlprefix = settings.get("urlprefix","") urlcacheid = settings.get("urlcacheid","gengine") force_https = asbool(settings.get("force_https",False)) init_reverse_proxy(force_https,urlprefix) urlcache_url = settings.get("urlcache_url","127.0.0.1:11211") urlcache_active = asbool(os.environ.get("URLCACHE_ACTIVE", settings.get("urlcache_active",True))) #auth def get_user(request): if not asbool(settings.get("enable_user_authentication",False)): return None token = request.headers.get('X-Auth-Token') if token is not None: from gengine.app.model import DBSession, AuthUser, AuthToken tokenObj = DBSession.query(AuthToken).filter(AuthToken.token==token).first() user = None if tokenObj and tokenObj.valid_until<datetime.datetime.utcnow(): tokenObj.extend() if tokenObj: user = tokenObj.user if not user: raise APIError(401, "invalid_token", "Invalid token provided.") if not user.active: raise APIError(404, "user_is_not_activated", "Your user is not activated.") return user return None def get_permissions(request): if not asbool(settings.get("enable_user_authentication", False)): return [] from gengine.app.model import DBSession, t_auth_tokens, t_auth_users, t_auth_roles, t_auth_roles_permissions, t_auth_users_roles from sqlalchemy.sql import select j = t_auth_tokens.join(t_auth_users).join(t_auth_users_roles).join(t_auth_roles).join(t_auth_roles_permissions) q = select([t_auth_roles_permissions.c.name],from_obj=j).where(t_auth_tokens.c.token==request.headers.get("X-Auth-Token")) return [r["name"] for r in DBSession.execute(q).fetchall()] def has_perm(request, name): return name in request.permissions config.add_request_method(get_user, 'user', reify=True) config.add_request_method(get_permissions, 'permissions', reify=True) config.add_request_method(has_perm, 'has_perm') #config.add_renderer(".html", "pyramid.mako_templating.renderer_factory") #routes from gengine.app.route import config_routes as config_app_routes config.include(config_app_routes, route_prefix=urlprefix) config.add_route('admin_app', '/admin/*subpath') from gengine.app.admin import init_admin as init_tenantadmin init_tenantadmin(urlprefix=urlprefix, secret=settings.get("flaskadmin_secret","fKY7kJ2xSrbPC5yieEjV")) #date serialization json_renderer = JSON() def datetime_adapter(obj, request): return obj.isoformat() json_renderer.add_adapter(datetime.datetime, datetime_adapter) config.add_renderer('json', json_renderer) config.scan() return HTTPSProxied(config.make_wsgi_app())
for test in unittest.defaultTestLoader.loadTestsFromModule(mod): suite.addTests(test) return suite if __name__ == "__main__": exit = 1 try: redis = testing.redis.RedisServer() from gengine.base.cache import setup_redis_cache dsn = redis.dsn() setup_redis_cache(dsn["host"], dsn["port"], dsn["db"]) from gengine.app.cache import init_caches init_caches() db.setupDB() testSuite = create_test_suite() text_runner = unittest.TextTestRunner(failfast=True).run(testSuite) if text_runner.wasSuccessful(): exit = 0 finally: try: db.unsetupDB() except: log.exception() try: redis.stop() except: log.exception()