Example #1
0
def main(global_config, **settings):
    engine = engine_from_config(settings)
    models.initialize_sql(engine)

    authn_policy = AuthTktAuthenticationPolicy(
            settings['auth.secret'])
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings,
            authentication_policy=authn_policy,
            authorization_policy=authz_policy,
            root_factory=RootFactory)
    config.add_route('games', '/api/games')
    config.add_route('view_game', '/api/games/{game_id}')
    config.add_route('make_move', '/api/games/{game_id}/move')
    config.add_route('resign', '/api/games/{game_id}/resign')
    config.add_route('offer_draw', '/api/games/{game_id}/offerdraw')
    config.add_route('accept_draw', '/api/games/{game_id}/acceptdraw')
    config.add_route('users', '/api/users')
    config.add_route('view_user', '/api/users/{user_id}')
    config.add_route('home', '/')
    config.add_route('register', '/register')
    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_static_view(name='static',
            path=os.path.join(here, 'static'))
    config.scan(views)
    app = config.make_wsgi_app()
    return app
Example #2
0
def make_wsgi_app(**kwargs):
    # Settings inheritance: env ini overrides default ini
    env = kwargs.pop('env')
    env_settings_file = f'{env}.ini'
    settings = ConfigParser()
    settings.read('default.ini')
    settings.read(env_settings_file)

    with Configurator(settings=settings) as config:
        # Db configuration
        # config.scan('models')
        db_uri_from_env(settings)
        engine = engine_from_config(settings['db:main'])
        initialize_sql(engine)
        config.registry.dbmaker = sessionmaker(bind=engine)
        config.add_request_method(db_session_maker, reify=True)
        print('Connected to Db', engine)

        # Dynamic routes handling
        routes_l = [route_cls() for route_cls in routes.__all__]
        for route in routes_l:
            config.add_route(route.name, route.url)
            config.add_view(route.handler, route_name=route.name)
        print('Imported routes: %s' % ', '.join(
            str(r)
            for r in routes_l) if routes_l else 'Empty /routes directory.')

        # Static assets views
        setup = config.get_settings()
        for asset_type, uri in setup.get('assets:main').items():
            config.add_static_view(path=f'app:{asset_type}', name=uri)

        return config.make_wsgi_app()
Example #3
0
 def setup_class(cls):
     models.initialize_sql(':memory:')
     cls._cm = models.ConfigManager()
     
     tank = models.Tank('TestTank')
     cls._cm.add(tank)
     cls._tank = tank
Example #4
0
def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.include("cornice")
    config.scan("crawdad.views")
    engine = create_engine(db_url)
    initialize_sql(engine)
    return config.make_wsgi_app()
Example #5
0
def main(global_config, **settings):
    config = Configurator(settings=settings)
    config.include("cornice")
    config.scan("metamkt.views")

    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)

    return config.make_wsgi_app()
Example #6
0
def main():
    dir=os.path.join(os.getcwd(), "db")
    file=os.path.join(dir, "database.sqlite")

    print("Initializing engine")
    engine = create_engine(('sqlite:///{0}').format(file), echo=True)
    initialize_sql(engine)

    print("Initializing application")
    app = QApplication(sys.argv)
    form = StockManager()
    form.show()
    app.exec_()
Example #7
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    FORMAT = '%(asctime)-15s [%(levelname)s] %(message)s'
    logging.basicConfig(format=FORMAT)

    log = logging.getLogger(__name__)
    if 'ssh.connection_params' in settings:
        if not os.path.exists(settings['ssh.connection_params']):
            log.error('File containing SSH connection parameters does not exist')
            exit(2)
        with open(settings['ssh.connection_params']) as f:
            ssh_param = jsonpickle.decode(f.read())
    else:
        raise BaseException('SSH Connection parameters file is not specified. See README')

    config = Configurator(settings=settings)
    config.scan('models') # the "important" line
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)

    config.include('pyramid_chameleon')
    config.registry.settings['ssh_holder'] = SSHConnectionHolder(ssh_param)

    fm = FileMonitor(SSHFileBrowser(config.registry.settings['ssh_holder']))
    print(fm.get_monitored_files())
    print(fm.validate_files_in_place())

    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('job_details', '/jobdetails/{jobid}')
    config.add_route('cancel_job', '/canceljob/{jobid}')
    config.add_route('cancel_job_basic', '/canceljob')
    config.add_route('joboutput', '/joboutput/{jobid}')

    config.add_route('send_job', '/sendjob/{action}')
    config.add_route('variable_environment', '/variable_environment/{action}')

    config.add_route('jobarchive', '/archive')
    config.add_route('jobarchive_config', '/archive/config')

    config.add_route('dashboard', '/dashboard')
    config.add_route('dashboard_statistics', '/dashboard/{fieldname}/json')

    config.add_route('filemonitor', '/filemonitor')
    config.add_route('filemonitor_editor', '/filemonitor/{modus}/{options}')
    config.add_route('filebrowser', '/browser')

    config.add_route('sshconfiguration', '/sshconfiguration')
    config.add_route('jobs', '/')
    config.scan()
    return config.make_wsgi_app()
Example #8
0
def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    initialize_sql(engine)
    
    config = Configurator(settings=settings)
    config.include('pyramid_chameleon')
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('deal', '/deal')
    config.add_route('hit', '/hit')
    config.add_route('stand', '/stand')
    config.add_route('split', '/split')
    config.add_route('double', '/double')
    config.add_route('surrender', '/surrender')
    config.scan()
    return config.make_wsgi_app()
Example #9
0
                               email=data.get('author_email'))
                    session.add(a)

                a = Author.query.filter_by(name=data['author']).one()
                r.author = a

            if 'license' in data:
                query = License.query.filter_by(name=data['license'])
                if query.count() == 0:
                    l = License(name=data['license'])
                    session.add(l)

                l = License.query.filter_by(name=data['license']).one()
                r.license = l

            session.add(r)

    session.commit()


if __name__ == '__main__':
    print "Initializing Smarmy..."
    engine = create_engine('sqlite:///smarmy.db')
    initialize_sql(engine)
    try:
        populate()
        print "Complete!"
    except IntegrityError, e:
        print "Got an Integrity Error:", str(e)
        DBSession.rollback()
Example #10
0
def main(global_config, **settings):
    settings = load_usermanager(settings)
    settings = load_database_settings(settings)

    secrethash = settings['secret'] if 'secret' in settings else 'sosecret'
    authn_policy = AuthTktAuthenticationPolicy(secrethash, callback=settings['usermanager'].groupfinder,
                                               hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    config = Configurator(settings=settings, root_factory=root_factory(settings))
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)
    config.registry.settings['directory_settings'] = dict()

    log.info('Engine from config')
    config.scan('models')
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)

    # load directory settings
    log.info('Load settings')
    DirectoryLoadSettings().load_server_settings(config.registry.settings['root_dir'], config)

    log.info('Adding routes')
    dir_path = r'([\w\-\_]*\/)*'
    file_basename = r'[\w\-\_\.]*'

    config.add_route('login', '/login')
    config.add_route('logout', '/logout')
    config.add_route('usermanagement', '/um')
    config.add_route('usermanagement_action', '/um/{action}/{id}')

    fileroutes = [dict(route_name='markdown', file_extension='\.md', options=None),
                  dict(route_name='csv', file_extension='\.csv', options=None),
                  dict(route_name='csv_delimiter', file_extension='\.csv', options='/{delimiter}'),
                  dict(route_name='matlab', file_extension='\.m', options=None),
                  dict(route_name='matlabfileviewer', file_extension='\.mat', options=None),
                  dict(route_name='matlabfileviewer_subpath', file_extension='\.mat', options='/{subkeypath}'),
                  dict(route_name='jsonviewer', file_extension='\.json', options=None),
                  dict(route_name='jsonviewer_plain', file_extension='\.json', options='/json')]
    for fileroute in fileroutes:
        options = '' if fileroute['options'] is None else fileroute['options']
        options = options if options.startswith('/') or options == '' else '/' + options
        filepath = '/{file:' + dir_path + file_basename + fileroute['file_extension'] + '}'
        config.add_route(fileroute['route_name'], filepath + options)

    config.add_route('directory', '/{dir:' + dir_path + '}')
    config.add_route('static', '/_static/*subpath')
    config.add_route('files_comment', '/{file:' + dir_path + file_basename + '}/{action:comment}', permission='authenticatedusers')
    config.add_route('files', '/*subpath', permission='authenticatedusers')

    log.info('Add views')
    here = lambda p: os.path.join(os.path.abspath(os.path.dirname(__file__)), p)
    static = static_view(here('static'), use_subpath=True)
    files = static_view(
        os.path.abspath(config.registry.settings['root_dir']),
        use_subpath=True)

    config.add_view(static, route_name='static')
    config.add_view(files, route_name='files', permission='authenticatedusers')
    config.scan()

    log.info('Start app')
    return config.make_wsgi_app()
Example #11
0
 def setup_class(cls):
     models.initialize_sql(':memory:')
     cls._cm = models.ConfigManager()
Example #12
0
            add_dependencies(_new_package, session)

        dep_as_package = base_query.one()

        if dep_as_package not in package.dependencies:
            package.dependencies.append(dep_as_package)

    print "package: %s has (%i/%i) deps" % (
        package.name, len(package.dependencies), len(deps))

    session.flush()


def build_comps():
    import subprocess
    subprocess.call('git clone git://git.fedorahosted.org/comps.git',
                    shell=True)
    subprocess.call('make comps-f16.xml', cwd='comps', shell=True)


if __name__ == '__main__':
    print "Initializing LeafyMiracle..."
    engine = create_engine('sqlite:///leafymiracle.db')
    initialize_sql(engine)
    build_comps()
    try:
        populate()
        print "Complete!"
    except IntegrityError, e:
        DBSession.rollback()
Example #13
0
def main(global_config, **settings):

  """ Setup the config
  """
  global tim_config
  tim_config = load_configuration('{TIM_CONFIG}/config.ini')

  # load the oauth configuration settings
  global oauth_config
  oauth_config = tim_config['oauth']

  """ This function returns a Pyramid WSGI application.
  """
  engine = engine_from_config(settings, 'sqlalchemy.')
  initialize_sql(engine)

  authn_policy = AuthTktAuthenticationPolicy('tim_secret', callback=groupfinder, timeout=1800, reissue_time=180, max_age=1800, debug=True)
  authz_policy = ACLAuthorizationPolicy()

  session_factory = pyramid_beaker.session_factory_from_settings(settings)

  config = Configurator(settings=settings,
                        root_factory='timmobile.context.RootFactory',
                        authentication_policy=authn_policy,
                        authorization_policy=authz_policy,
                        session_factory=session_factory)

  config.add_static_view('static', 'timmobile:static', cache_max_age=0)
  config.add_static_view('img', 'timmobile:img', cache_max_age=0)
  config.add_static_view('css', 'timmobile:css', cache_max_age=0)
  config.add_static_view('js', 'timmobile:js', cache_max_age=0)

  # define routes
  #
  config.add_route('home', '/')

  config.add_route('login', '/login')
  config.add_route('logout', '/logout')

  config.add_route('newlogin', '/newlogin')
  config.add_route('accounts', '/accounts')
  config.add_route('account_details', '/accounts/{featurename}')
  config.add_route('newsfeed', '/newsfeed')

  config.add_route('timeline', '/{authorname}/timeline')

  config.add_route('profile', '/{authorname}/profile')
  config.add_route('followers', '/followers')

  #
  # oauth setup paths
  #

  # twitter oauth
  config.add_route('twitter', '/oauth/twitter')
  config.add_route('twitter_callback', '/oauth/twitter/callback')

  # facebook auth
  config.add_route('facebook', '/oauth/facebook')
  config.add_route('facebook_callback', '/oauth/facebook/callback')

  # linkedin auth
  config.add_route('linkedin', '/oauth/linkedin')
  config.add_route('linkedin_callback', '/oauth/linkedin/callback')

  # google+ auth
  config.add_route('googleplus', '/oauth/googleplus')
  config.add_route('googleplus_callback', '/oauth/googleplus/callback')

  # instagram auth
  config.add_route('instagram', '/oauth/instagram')
  config.add_route('instagram_callback', '/oauth/instagram/callback')

  # flickr auth
  config.add_route('flickr', '/oauth/flickr')
  config.add_route('flickr_callback', '/oauth/flickr/callback')

  # foursquare auth
  config.add_route('foursquare', '/oauth/foursquare')
  config.add_route('foursquare_callback', '/oauth/foursquare/callback')

  # generic oauth
  config.add_route('oauth', '/oauth/{featurename}')
  config.add_route('oauth_callback', '/oauth/{featurename}/callback')

  config.scan()

  return config.make_wsgi_app()
Example #14
0
                    this.app.event(ev)
            # Render the game
            rect = this.app.get_render_area()
            updates = []
            this.disp.set_clip(rect)
            lst = this.render(this.disp, rect)
            if (lst):
                updates += lst
            this.disp.set_clip()

            # Cap it at 30fps
            this.clock.tick(30)

            # Give pgu a chance to update the display
            lst = this.app.update()
            if (lst):
                updates += lst
            pygame.display.update(updates)
            pygame.time.wait(10)



initialize_sql()
datastore = DataStore()
#disp = pygame.display.set_mode((1024, 768))
disp = pygame.display.set_mode((800, 600))
#disp = pygame.display.set_mode((800, 600), FULLSCREEN)
eng = GameEngine(disp, datastore)
eng.run()

Example #15
0
import discord
import traceback
import config

from models import initialize_sql
from discord.ext import commands

cogs_extensions = ["cogs.events", "cogs.commands", "cogs.error_handler"]

bot = commands.Bot(command_prefix='$', description='playground')

if __name__ == "__main__":

    initialize_sql('', None)

    for extension in cogs_extensions:
        try:
            bot.load_extension(extension)
            print('Successfully loaded extension {0}'.format(extension))
        except (discord.ClientException, ModuleNotFoundError):
            print('Failed to load extension {0}.'.format(extension))
            traceback.print_exc()

    bot.run(config.bot_token, bot=True, reconnect=True)
Example #16
0
def appmaker(engine):
    initialize_sql(engine)
    return default_get_root
Example #17
0
""" Setup and utility methods for the Flask-RESTful API """
import flask_restful
from flask_restful import abort
from datetime import datetime
from json import JSONEncoder
import dateutil.parser
import models

api = flask_restful.Api()
models.initialize_sql('reefpi.db')
event_manager = models.EventManager()
config_manager = models.ConfigManager()

def try_parse_time(date):
    """ Attempt to parse a time and abort HTTP 400 if dateutil can't figure it out """
    try:
        return dateutil.parser.parse(date)
    except ValueError:
        abort(400, message="Unable to parse '{}' into datetime".format(date))

def try_get_time(args, key):
    """ Attempt to get and parse a time from a dict, aborting HTTP 400 if the key is not present """
    try:
        return try_parse_time(args[key])
    except KeyError:
        abort(400, message="Unable to parse '{}' parameter into datetime: no such parameter was supplied".format(key))

class ModelEncoder(JSONEncoder):
    """ Custom JSON encoder for objects in the models module """
    def default(self, o):
        json = None
Example #18
0
def appmaker(engine):
    initialize_sql(engine)
    return default_get_root
Example #19
0
def _initTestingDB():
    from models import DBSession
    from models import Base
    from sqlalchemy import create_engine
    engine = create_engine('sqlite://')
    return initialize_sql(engine)
	def create_db(self):
		# creo il db e tutte le tabelle nel database
		out = models.initialize_sql()
		return "DB creato, Tabelle Create."
Example #21
0
from tqdm import tqdm
from sqlalchemy import create_engine
from models import initialize_sql
from models.menu import Menu
from models.menuItem import MenuItem
from models.menuPage import MenuPage
from models.dish import Dish

# FIRST SET UP POSTGRES:
# CREATE DATABASE menus;
# CREATE USER thiccdata WITH PASSWORD 'hablab';
# GRANT ALL PRIVILEGES ON DATABASE menus TO thiccdata;

engine = create_engine(
    'postgresql+psycopg2://thiccdata:hablab@localhost/menus', echo=False)
session = initialize_sql(engine)

data_path = '/Users/grant/Documents/hablab-thiccdata/raw_data'
#
# with open(os.path.join(data_path, "Menu.csv"), "r") as f:
#     reader = csv.reader(f, delimiter=",")
#     next(reader)
#     iteration = 0
#     for line in tqdm(reader):
#         m = session.query(Menu).filter(Menu.id == line[0]).all()
#         if len(m) == 0:
#             iteration += 1
#             menu = Menu(
#                 id=line[0],
#                 name=line[1],
#                 sponsor=line[2],
Example #22
0
def setup_database(settings={
    'sqlalchemy.url': 'sqlite:///:memory:',
}):
    engine = engine_from_config(settings, 'sqlalchemy.')
    initialize_sql(engine)