예제 #1
0
def test_render_default():
    conf = AppConfig(minimal=True)
    conf.default_renderer = 'json'
    app = conf.make_wsgi_app()

    res = tg.render_template({'value': 'value'})
    assert 'value": "value' in res
예제 #2
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_disconnect_hooks_multiple_listener(self):
        hook1_has_been_called = []
        def hook1_listener():
            hook1_has_been_called.append(True)

        hook2_has_been_called = []
        def hook2_listener():
            hook2_has_been_called.append(True)

        class RootController(TGController):
            @expose()
            def test(self):
                tg.hooks.notify('custom_hook', controller=RootController.test)
                return 'HI!'

        conf = AppConfig(minimal=True, root_controller=RootController())
        tg.hooks.register('custom_hook', hook1_listener)
        tg.hooks.register('custom_hook', hook2_listener)
        conf.package = PackageWithModel()
        app = conf.make_wsgi_app()
        app = TestApp(app)

        app.get('/test')
        app.get('/test')
        tg.hooks.disconnect('custom_hook', hook2_listener)
        app.get('/test')

        # Disconnecting an unregistered hook should do nothing.
        tg.hooks.disconnect('unregistered', hook1_listener)

        assert len(hook1_has_been_called) == 3, hook1_has_been_called
        assert len(hook2_has_been_called) == 2, hook2_has_been_called
예제 #3
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_config_hooks(self):
        class RootController(TGController):
            @expose()
            def test(self):
                return 'HI!'

        visited_hooks = []
        def before_config_hook(app):
            visited_hooks.append('before_config')
            return app
        def after_config_hook(app):
            visited_hooks.append('after_config')
            return app
        def configure_new_app_hook(app):
            assert isinstance(app, TGApp)
            visited_hooks.append('configure_new_app')

        conf = AppConfig(minimal=True, root_controller=RootController())
        tg.hooks.register('before_config', before_config_hook)
        tg.hooks.register('after_config', after_config_hook)
        tg.hooks.register('configure_new_app', configure_new_app_hook)
        app = conf.make_wsgi_app()
        app = TestApp(app)

        assert 'HI!' in app.get('/test')
        assert 'before_config' in visited_hooks
        assert 'after_config' in visited_hooks
        assert 'configure_new_app' in visited_hooks
예제 #4
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_startup_hook_with_exception(self):
        def func():
            raise Exception

        tg.hooks.register('startup', func)
        conf = AppConfig(minimal=True)
        app = conf.make_wsgi_app()
예제 #5
0
 def setup(self):
     conf = AppConfig(minimal=True)
     conf.use_dotted_templatenames = True
     conf.renderers.append('mako')
     conf.package = FakePackage()
     self.conf = conf
     self.app = conf.make_wsgi_app()
예제 #6
0
def test_render_default():
    conf = AppConfig(minimal=True)
    conf.default_renderer = 'json'
    app = conf.make_wsgi_app()

    res = tg.render_template({'value': 'value'})
    assert 'value": "value' in res
예제 #7
0
 def setup(self):
     conf = AppConfig(minimal=True)
     conf.use_dotted_templatenames = True
     conf.renderers.append('mako')
     conf.package = FakePackage()
     self.conf = conf
     self.app = conf.make_wsgi_app()
예제 #8
0
def make_app(controller_klass=None, environ=None, config_options=None, with_errors=False,
             make_app=True):
    """Creates a `TestApp` instance."""
    if controller_klass is None:
        controller_klass = TGController

    conf = AppConfig(root_controller=ControllerWrap(controller_klass),
                     **default_config)

    # Just let exceptions crash.
    conf['trace_errors.enable'] = False

    if with_errors:
        conf['errorpage.enabled'] = True
        conf['errorpage.status_codes'] = [403, 404]
    else:
        conf['errorpage.enabled'] = False

    conf['session.enabled'] = True
    conf['session.data_dir'] = session_dir
    conf['cache.enabled'] = True
    conf['cache.cache_dir'] = cache_dir

    if config_options is not None:
        for k, v in config_options.items():
            conf[k] = v

    if make_app:
        return TestApp(conf.make_wsgi_app())
    else:
        return conf
예제 #9
0
 def setup(self):
     conf = AppConfig(minimal=True)
     conf.use_dotted_templatenames = True
     conf.renderers.append('kajiki')
     conf.package = FakePackage()
     self.conf = conf
     self.app = TestApp(conf.make_wsgi_app())
     self.render = tg.config['render_functions']['kajiki']
예제 #10
0
 def setup(self):
     conf = AppConfig(minimal=True)
     conf.use_dotted_templatenames = True
     conf.renderers.append('kajiki')
     conf.package = FakePackage()
     self.conf = conf
     self.app = TestApp(conf.make_wsgi_app())
     self.render = tg.config['render_functions']['kajiki']
예제 #11
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_dedicated_controller_wrapper_after_milestone_reached(self):
        conf = AppConfig(minimal=True)

        def f():
            pass

        milestones.environment_loaded.reach()
        conf.register_controller_wrapper(None, controller=f)
예제 #12
0
    def setup(self):
        class RootController(TGController):
            @expose()
            def test(self):
                return str(bool(EqualsTwo()))

        conf = AppConfig(minimal=True, root_controller=RootController())
        app = conf.make_wsgi_app()
        self.app = TestApp(app)
예제 #13
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_startup_hook(self):
        executed = []
        def func():
            executed.append(True)

        tg.hooks.register('startup', func)
        conf = AppConfig(minimal=True)
        app = conf.make_wsgi_app()
        assert True in executed, executed
예제 #14
0
def run():
    global userconfig
    global httpd
    config = AppConfig(minimal=True, root_controller=RootController())
    config['helpers'] = webhelpers2
    config.renderers = ['kajiki']
    config.serve_static = True
    config.paths['static_files'] = 'web/public'
    application = config.make_wsgi_app()

    print("Serving on port " + userconfig['Web']['porttoserve'] + "...")
    httpd = make_server('', int(userconfig['Web']['porttoserve']), application, 3)
    httpd.serve_forever()
예제 #15
0
파일: test_i18n.py 프로젝트: TurboGears/tg2
 def setup(self):
     conf = AppConfig(minimal=True, root_controller=i18nRootController())
     conf['paths']['root'] = 'tests'
     conf['i18n.enabled'] = True
     conf['session.enabled'] = True
     conf['i18n.lang'] = 'kr'
     conf['beaker.session.key'] = 'tg_test_session'
     conf['beaker.session.secret'] = 'this-is-some-secret'
     conf.renderers = ['json']
     conf.default_renderer = 'json'
     conf.package = _FakePackage()
     app = conf.make_wsgi_app()
     self.app = TestApp(app)
예제 #16
0
def test_jinja_lookup_nonexisting_template():
    conf = AppConfig(minimal=True)
    conf.use_dotted_templatenames = True
    conf.renderers.append('jinja')
    conf.package = FakePackage()
    app = conf.make_wsgi_app()

    from jinja2 import TemplateNotFound
    try:
        render_jinja = tg.config['render_functions']['jinja']
        render_jinja('tg.this_template_does_not_exists',
                     {'app_globals':tg.config['tg.app_globals']})
        assert False
    except TemplateNotFound:
        pass
예제 #17
0
def test_jinja_lookup_nonexisting_template():
    conf = AppConfig(minimal=True)
    conf.use_dotted_templatenames = True
    conf.renderers.append('jinja')
    conf.package = FakePackage()
    app = conf.make_wsgi_app()

    from jinja2 import TemplateNotFound
    try:
        render_jinja = tg.config['render_functions']['jinja']
        render_jinja('tg.this_template_does_not_exists',
                     {'app_globals': tg.config['tg.app_globals']})
        assert False
    except TemplateNotFound:
        pass
예제 #18
0
def run_api():
    global userconfig
    try:
        port = userconfig['Web']['apiport']
    except KeyError:
        port = '9380'
    global httpd
    config = AppConfig(minimal=True, root_controller=APIRootController())
    config['helpers'] = webhelpers2
    config.renderers = ['kajiki']
    config.serve_static = False
    application = config.make_wsgi_app()

    print("Serving APIs on port " + port + "...")
    httpd = make_server('', int(port), application, 3)
    httpd.serve_forever()
예제 #19
0
    def test_test_context_broken_app(self):
        from webtest import TestApp
        from tg import AppConfig, config
        from tg.request_local import context

        app = TestApp(
            AppConfig(minimal=True, root_controller=None).make_wsgi_app())

        try:
            with test_context(app):
                raise RuntimeError('This is an error')
        except RuntimeError:
            pass
        else:
            assert False, 'Should have raised RuntimeError...'

        with test_context(app):
            config._pop_object()
        # Check that context got cleaned up even though config caused an exception
        assert not context._object_stack()

        with test_context(app):
            context._pop_object()
        # Check that config got cleaned up even though context caused an exception
        assert not config._object_stack()
예제 #20
0
def testWebServer():
    print("Hosting server")

    config = AppConfig(minimal=True, root_controller=RootController())

    application = config.make_wsgi_app()

    httpd = make_server('', 62433, application)

    thr = threading.Thread(target=httpd.serve_forever)
    thr.start()

    print("Running test")
    page = urllib.request.urlopen('http://127.0.0.1:62433/')
    if page.read().decode() != "Hello World":
        raise RuntimeError("Server did not correctly host 'Hello World' page.")
    httpd.shutdown()
예제 #21
0
def testWebServer():
    print("Hosting server")

    config = AppConfig(minimal=True, root_controller=RootController())

    application = config.make_wsgi_app()

    httpd = make_server('', 62433, application)

    thr = threading.Thread(target=httpd.serve_forever)
    thr.start()

    print("Running test")
    page = request.urlopen('http://127.0.0.1:62433/')
    if page.read().decode() != "Hello World":
        raise RuntimeError("Server did not correctly host 'Hello World' page.")
    httpd.shutdown()
예제 #22
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_controller_hooks_with_value(self):
        # Reset milestone so that registered hooks
        milestones._reset_all()

        class RootController(TGController):
            @expose()
            def test(self):
                return tg.hooks.notify_with_value('test_hook', 'BO',
                                                  controller=RootController.test)

        def value_hook(value):
            return value*2

        tg.hooks.register('test_hook', value_hook, controller=RootController.test)

        conf = AppConfig(minimal=True, root_controller=RootController())
        app = conf.make_wsgi_app()
        app = TestApp(app)

        resp = app.get('/test')
        assert 'BOBO' in resp, resp
예제 #23
0
파일: test_hooks.py 프로젝트: softtiny/tg2
    def test_disconnect_hooks(self):
        hook1_has_been_called = []
        def hook1_listener():
            hook1_has_been_called.append(True)

        class RootController(TGController):
            @expose()
            def test(self):
                tg.hooks.notify('custom_hook')
                return 'HI!'

        conf = AppConfig(minimal=True, root_controller=RootController())
        tg.hooks.register('custom_hook', hook1_listener)
        conf.package = PackageWithModel()
        app = conf.make_wsgi_app()
        app = TestApp(app)

        app.get('/test')
        app.get('/test')
        tg.hooks.disconnect('custom_hook', hook1_listener)
        app.get('/test')

        assert len(hook1_has_been_called) == 2, hook1_has_been_called
예제 #24
0
파일: __init__.py 프로젝트: softtiny/tg2
    def __init__(self, folder, values=None):
        if values is None:
            values = {}
        AppConfig.__init__(self)

        # First we setup some base values that we know will work
        self.renderers = ['genshi', 'mako', 'jinja', 'json', 'jsonp', 'kajiki']
        self.render_functions = tg.util.Bunch()
        self.package = tests.test_stack
        self.default_renderer = 'kajiki'
        self.globals = self
        self.auth_backend = None
        self.auto_reload_templates = False
        self.use_legacy_renderer = False
        self.use_dotted_templatenames = False
        self.serve_static = False
        self['errorpage.enabled'] = False
        self['trace_errors.enable'] = False
        self['trace_slowreqs.enable'] = False

        root = os.path.dirname(os.path.dirname(tests.__file__))
        test_base_path = os.path.join(
            root,
            'tests',
            'test_stack',
        )
        test_config_path = os.path.join(test_base_path, folder)
        self.paths = tg.util.Bunch(
            root=test_base_path,
            controllers=os.path.join(test_config_path, 'controllers'),
            static_files=os.path.join(test_config_path, 'public'),
            templates=[os.path.join(test_config_path, 'templates')],
            i18n=os.path.join(test_config_path, 'i18n'))

        # then we override those values with what was passed in
        for key, value in values.items():
            setattr(self, key, value)
예제 #25
0
class WebInterface(Interface):
    __logger=logging.getLogger(__name__)
    config=None
    httpd=None
    application=None
    keep_running=True
    player=None
    controller=None
    
    def __init__(self, templatePath, staticPath, port, controller):
        self.__logger.debug("create WebInterface Instance")
  
        self.__logger.debug("setup TurboGears2")
        self.controller = controller
        self.config = AppConfig(minimal=True, root_controller=self.controller)
        
        #jinja stuff
        self.config.renderers.append('jinja')
        self.config.default_renderer = 'jinja'
        self.config.use_dotted_templatenames = False
        self.config.paths['templates'] = [templatePath]
        
        #statics
        self.config.serve_static = True
        self.config.paths['static_files'] = staticPath
        
        #make wsgi_app
        self.application = self.config.make_wsgi_app()
        
        #make wsgi_server
        self.httpd = make_server('', port, self.application, ThreadingWSGIServer)
        self.httpd.timeout = 5
    
    def run(self):
        self.__logger.debug("run")
        while(self.keep_running):
            self.__logger.info("listening for Requests")
            try:
                self.httpd.serve_forever()
            except KeyboardInterrupt:
                self.shutdown()
    
    def shutdown(self):
        self.__logger.info("init shutdown")
        service.stop()
        self.keep_running=False
예제 #26
0
def start_server():
    """ start webserver """

    catalog_engine = create_engine(SQLITE_DATA_TARGET)
    login_engine = create_engine(LOGIN_DATA_TARGET)
    config = AppConfig(minimal=True,
                       root_controller=RootController(catalog_engine,
                                                      login_engine))
    config.sa_auth.charset = 'utf-8'
    config.renderers = ['kajiki']
    config.default_renderer = 'kajiki'
    config.serve_static = True
    config.paths['static_files'] = 'public'
    config.paths['controllers'] = 'controllers'

    application = config.make_wsgi_app()
    print "Serving on port 8080..."
    httpd = make_server('', 8080, application)
    httpd.serve_forever()
예제 #27
0
파일: test_i18n.py 프로젝트: softtiny/tg2
 def setup(self):
     conf = AppConfig(minimal=True, root_controller=i18nRootController())
     conf['paths']['root'] = 'tests'
     conf['i18n.enabled'] = True
     conf['session.enabled'] = True
     conf['i18n.lang'] = 'kr'
     conf['beaker.session.key'] = 'tg_test_session'
     conf['beaker.session.secret'] = 'this-is-some-secret'
     conf.renderers = ['json']
     conf.default_renderer = 'json'
     conf.package = _FakePackage()
     app = conf.make_wsgi_app()
     self.app = TestApp(app)
예제 #28
0
def run():
    global userconfig
    try:
        port = userconfig['Web']['porttoserve']
    except AttributeError:
        port = '9375'
    global httpd
    config = AppConfig(minimal=True, root_controller=RootController())
    config['helpers'] = webhelpers2
    config.renderers = ['kajiki']
    config.serve_static = True
    config.paths['static_files'] = 'web/public'
    application = config.make_wsgi_app()

    print("Serving on port " + port + "...")
    httpd = make_server('', int(port), application, 3)
    httpd.serve_forever()
예제 #29
0
   def __init__(self, templatePath, staticPath, port, controller):
       self.__logger.debug("create WebInterface Instance")
 
       self.__logger.debug("setup TurboGears2")
       self.controller = controller
       self.config = AppConfig(minimal=True, root_controller=self.controller)
       
       #jinja stuff
       self.config.renderers.append('jinja')
       self.config.default_renderer = 'jinja'
       self.config.use_dotted_templatenames = False
       self.config.paths['templates'] = [templatePath]
       
       #statics
       self.config.serve_static = True
       self.config.paths['static_files'] = staticPath
       
       #make wsgi_app
       self.application = self.config.make_wsgi_app()
       
       #make wsgi_server
       self.httpd = make_server('', port, self.application, ThreadingWSGIServer)
       self.httpd.timeout = 5
예제 #30
0
def make_appcfg_for_controller(root_controller):
    config = AppConfig(minimal=True, root_controller=root_controller)
    config['helpers'] = Bunch()
    config['app_globals'] = AppGlobals
    return config
예제 #31
0
    @expose("json")
    def queries(self, queries=1):
        num_queries = getQueryNum(queries)
        rp = partial(randint, 1, 10000)
        get = db_session.query(World).get
        worlds = [get(rp()).serialize() for _ in xrange(num_queries)]
        return json.dumps(worlds)

    @expose()
    def fortune(self):
        fortunes = db_session.query(Fortune).all()
        fortunes.append(
            Fortune(id=0, message="Additional fortune added at request time."))
        fortunes.sort(key=attrgetter("message"))
        template = env.get_template("fortunes.html")
        return template.render(fortunes=fortunes)


config = AppConfig(minimal=True, root_controller=RootController())
config.renderers.append("jinja")

tg_app = config.make_wsgi_app()


def app(env, start):
    try:
        return tg_app(env, start)
    finally:
        db_session.close()
예제 #32
0
def configure_app(using):
    # Simulate starting configuration process from scratch
    milestones._reset_all()

    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['kajiki']
    app_cfg.default_renderer = 'kajiki'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = app_cfg['session.secret'] = 'SECRET'
    app_cfg.auth_backend = 'ming'
    app_cfg['mail.debugmailer'] = 'dummy'

    if using == 'sqlalchemy':
        app_cfg.package.model = FakeSQLAModel()
        app_cfg.use_sqlalchemy = True
        app_cfg['sqlalchemy.url'] = 'sqlite://'
        app_cfg.use_transaction_manager = True
    elif using == 'ming':
        app_cfg.package.model = FakeMingModel()
        app_cfg.use_ming = True
        app_cfg['ming.url'] = 'mim:///testregistration'
    else:
        raise ValueError('Unsupported backend')

    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    # CUSTOM registration options
    app_cfg['registration.email_sender'] = '*****@*****.**'

    from registration.lib import send_email, get_form

    # Guarantee that the same form is used between multiple
    # configurations of TGApps. Otherwise the validated
    # form would be different from the displayed one.
    plug_args = {}
    if '_pluggable_registration_config' in config:
        plug_args['form_instance'] = get_form()

    plug(app_cfg, 'tgext.mailer', plug_bootstrap=True, debugmailer='dummy')
    plug(app_cfg, 'registration', plug_bootstrap=False, **plug_args)
    return app_cfg
예제 #33
0
def test_render_missing_renderer():
    conf = AppConfig(minimal=True)
    app = conf.make_wsgi_app()

    tg.render_template({}, 'gensh')
예제 #34
0
 def setup_class(cls):
     config = AppConfig(minimal=True, root_controller=RootController())
     cls.wsgi_app = config.make_wsgi_app()
예제 #35
0
def configure_app(using):
    # Simulate starting configuration process from scratch
    milestones._reset_all()

    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['kajiki']
    app_cfg.default_renderer = 'kajiki'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg['tw2.enabled'] = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = app_cfg['session.secret'] = 'SECRET'
    app_cfg.auth_backend = 'ming'
    app_cfg['mail.debugmailer'] = 'dummy'

    if using == 'sqlalchemy':
        app_cfg.package.model = FakeSQLAModel()
        app_cfg.use_sqlalchemy = True
        app_cfg['sqlalchemy.url'] = 'sqlite://'
        app_cfg.use_transaction_manager = True
        app_cfg['tm.enabled'] = True
    elif using == 'ming':
        app_cfg.package.model = FakeMingModel()
        app_cfg.use_ming = True
        app_cfg['ming.url'] = 'mim:///testregistration'
    else:
        raise ValueError('Unsupported backend')

    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    # CUSTOM registration options
    app_cfg['registration.email_sender'] = '*****@*****.**' 

    plug(app_cfg, 'tgext.mailer', plug_bootstrap=True, debugmailer='dummy')
    plug(app_cfg, 'registration', plug_bootstrap=False, 
         form_instance=registration_form)
    
    return app_cfg
예제 #36
0
    def index(self):
        redirect("list/")

    @expose("list.jinja")
    def list(self):
        onlyfiles = [f for f in listdir("public/video") if isfile(join("public/video", f))]
        return dict(message="this is the list", files=onlyfiles)

    @expose("view.jinja")
    def view(self, vId=None):
        if vId is None:
            return dict(message="The video ID is invalid")
        return dict(
            message=vId,
            vid_url="/video/" + vId,
            data_obj=[{"serie": 0, "time": 0, "gamma": 1, "delta": 3, "theta": 1, "beta": 2, "alpha": 1}],
        )


# return dict(message=vId, vid_url="/video/"+vId, data_obj = [{"serie":0, "time":0, "gamma":1, "delta":3, "theta":1, "beta":2, "alpha":1}] )

config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ["jinja"]
config.serve_static = True
config.paths["static_files"] = "public"
application = config.make_wsgi_app()

print("Serving on port 8080...")
httpd = make_server("", 8080, config.make_wsgi_app())
httpd.serve_forever()
예제 #37
0
    @expose('json:', content_type='application/json')
    def timeline(self, **kw):
        f = open(TIMELINE_FILE)
        yield f.read()

    @expose('json:', content_type='application/json')
    def clusters(self, **kw):
        f = open(CLUSTERS_FILE)
        yield f.read()

    @expose('json:', content_type='application/json')
    def force(self, **kw):
        f = open(FORCE_FILE)
        yield f.read()

config = AppConfig(minimal=True, root_controller=RootController())

#Only change since before is that we register the 'json' renderer
#into our list of available renderers, so that we are able to
#encode our responses as JSON
config.renderers = ['json', 'jinja']
config.default_renderer = 'jinja'

config.serve_static = True
config['paths']['static_files'] = './'

from wsgiref.simple_server import make_server
print "Serving on port 8080..."
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
예제 #38
0
from wsgiref.simple_server import make_server
from tg import expose, TGController, AppConfig


class RootController(TGController):
    @expose()
    def index(self):
        return "<h1>Turbo Gears 2 Index</h1>"

    @expose()
    def hello(self, user=None):
        user = user or "World"
        return "Hello {0}!".format(user)


config = AppConfig(minimal=True, root_controller=RootController())

print "Serving on port 8080..."
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()
예제 #39
0

class RootController(TGController):
    @expose('new.xhtml')
    def new(self, **kw):
        tmpl_context.widget = new_city_form
        return dict(value=kw)

    @expose('new.xhtml')
    def old(self, **kw):
        tmpl_context.widget = new_movie_form
        return dict(value=kw)

    @expose()
    def index(self):
        return 'Hello World'

    @expose('templates.hello.xhtml')
    def hello(self, person=None):
        return dict(person=person)


config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ['kajiki']
application = config.make_wsgi_app()
from tw2.core.middleware import TwMiddleware
application = TwMiddleware(application)

from wsgiref.simple_server import make_server
httpd = make_server("", 8080, application)
httpd.serve_forever()
예제 #40
0
    app_globals.player = PlayMusicThread(gm=app_globals.gm,
                                         songsmap=dict(((song['id'], song) for song in app_globals.library)))
    app_globals.player.start()

def _setup_google_music():
    log.info('Connecting to Google Music')
    config = tg.config
    app_globals = config.tg.app_globals

    app_globals.gm = Webclient()
    app_globals.gm.login(config.gm.username, config.gm.password)

    song_sorting = lambda song: '%(artist)s-%(album)s-%(track)s' % song
    app_globals.library = sorted(app_globals.gm.get_all_songs(), key=song_sorting)

config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ['json']
config.default_renderer = 'json'
config.serve_static = True
config.paths['static_files'] = '.'
config.register_hook('startup', _setup_google_music)
config.register_hook('startup', _setup_music_player)

from wsgiref.simple_server import make_server
import json

config_options = {}
with open('config.json') as config_file:
    config_options.update(json.load(config_file))

print "Serving on port 8080..."
예제 #41
0
                        total_power += int(row['POTENZA_da_116_a_350_KW']) * ((116+350)/2.0)

                    if row['POTENZA_da_35_a_116_KW']:
                        total_power += int(row['POTENZA_da_35_a_116_KW']) * ((35+116)/2.0) 

                    if row['POTENZA_uguale_350_KW_e_maggiore']:
                        total_power += int(row['POTENZA_uguale_350_KW_e_maggiore']) * 350.0

                    if total_power:
                        pos = None
                        if addr_cache.has_key(row['toponimo']):
                            pos = addr_cache[row['toponimo']]

                        filtered_data.append({'location': row['toponimo'].lower(), 'power': total_power/1000, 'position': None})
            
        return dict(data=filtered_data)

    @expose()
    def save_geocode(self, addr, lng, lat):
        addr_cache[addr.encode('utf-8')] = (lng, lat)
        addr_cache.sync()
        return 'OK'

config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ['json']

print "Serving on port 8080..."
httpd = make_server('', 8080, config.make_wsgi_app())
httpd.serve_forever()

예제 #42
0
    def setUp(self):
        self.root_controller = self.controller_factory()
        conf = AppConfig(minimal=True, root_controller=self.root_controller)
        conf.package = FakePackage()
        conf.model = conf.package.model
        conf.use_dotted_templatenames = True
        conf.renderers = ['json', 'jinja', 'mako']
        conf.default_renderer = 'jinja'
        conf.use_sqlalchemy = True
        conf.paths = {'controllers':'tests',
                      'templates':['tests']}
        conf.disable_request_extensions = False
        conf.prefer_toscawidgets2 = True
        conf.use_transaction_manager = True
        conf['sqlalchemy.url'] = 'sqlite:///:memory:'

        self.app = TestApp(conf.make_wsgi_app())

        metadata.create_all()
예제 #43
0
def configure_app():
    app_cfg = AppConfig(minimal=True)
    app_cfg.renderers = ['genshi']
    app_cfg.default_renderer = 'genshi'
    app_cfg.use_dotted_templatenames = True
    app_cfg.package = FakeAppPackage()
    app_cfg.use_toscawidgets2 = True
    app_cfg['tw2.enabled'] = True
    app_cfg.sa_auth.authmetadata = TestAuthMetadata()
    app_cfg['beaker.session.secret'] = 'SECRET'
    app_cfg.auth_backend = 'sqlalchemy'
    app_cfg.sa_auth.cookie_secret = 'SECRET'
    app_cfg.package.model = FakeSQLAModel()
    app_cfg.use_sqlalchemy = True
    app_cfg['sqlalchemy.url'] = 'sqlite://'
    app_cfg.use_transaction_manager = True
    app_cfg['tm.enabled'] = True
    app_cfg.model = app_cfg.package.model
    app_cfg.DBSession = app_cfg.package.model.DBSession

    plug(app_cfg,
         'calendarevents',
         event_types=[FakeEventType()],
         global_models=False,
         plug_bootstrap=False,
         form_instance=calendar_form)

    # This is to reset @cached_properties so they get reconfigured for new backend

    return app_cfg
예제 #44
0
                    'clusters':clusters,
                    'cluster_counts':cluster_counts,
                    'degree_distribution':degree_distribution,
                    'degree':foaf_graph.degree(),
                    'top10':top10
                }
                foaf_data = json.dumps(infos)
                data_file.write(foaf_data)
                return foaf_data

    @expose(content_type='application/json')
    def graph(self, **kw):
        with closing(open('graph_cache.json', 'w')) as graph_file:
            foaf_graph = retrieve_foaf(FBTOKEN)                             
            foaf_graph_json = jg.dumps(foaf_graph)
            graph_file.write(foaf_graph_json)
            return foaf_graph_json
 
config = AppConfig(minimal=True, root_controller=RootController())
config.serve_static = True
config.paths['static_files'] = './'

config.renderers = ['jinja', 'json']
config.default_renderer = 'jinja'

application = config.make_wsgi_app()

print 'Serving on port 8080...'
httpd = make_server('', 8080, application)
httpd.serve_forever()
예제 #45
0
    model_json = model.to_json()
    with open(name, 'w') as json_file:
        json_file.write(model_json)
    model.save_weights(name + '.h5')


class RootController(TGController):
    @expose()
    def test(self, vector):
        vector = eval(vector)
        return test(np.array([vector]))

    @expose()
    def save(self, name):
        save(name)
        return 'ok'

    @expose()
    def train(self, vector, malwareClass):
        vector = eval(vector)
        train(vector, malwareClass)
        return 'ok'


config = AppConfig(minimal=True, root_controller=RootController())

application = config.make_wsgi_app()
print("Serving on port 3008...")
httpd = make_server('', 3008, application)
httpd.serve_forever()
__author__ = 'alexcomu'
from tg import AppConfig, TGController
from tg import expose

class RootController(TGController):
    @expose()
    def index(self):
        return 'Hello world'

config = AppConfig(minimal=True, root_controller=RootController())
application = config.make_wsgi_app()

from wsgiref.simple_server import make_server
print 'Serving on port 8080...'
httpd = make_server('', 8080, application)
httpd.serve_forever()
예제 #47
0
 def setup_class(cls):
     config = AppConfig(minimal=True, root_controller=RootController())
     config['csrf.secret'] = 'MYSECRET'
     cls.wsgi_app = config.make_wsgi_app()
예제 #48
0
from tg import expose, TGController, AppConfig

class RootController(TGController):
     @expose()
     def index(self):
         return "<h1>Hello World</h1>"

class RootController(TGController):
    @expose()
    def index(self):
        return 'Hello World'

    @expose('hello.jinja')
    def hello(self, person=None):
        return dict(person=person)

config = AppConfig(minimal=True, root_controller=RootController())
config.renderers = ['jinja']
config.serve_static = True
config.paths['static_files'] = 'public'

import webhelpers2
import webhelpers2.text
config['helpers'] = webhelpers2

application = config.make_wsgi_app()

print "Serving on port 80..."
httpd = make_server('', 80, application)
httpd.serve_forever()
예제 #49
0
 def setup_class(cls):
     config = AppConfig(minimal=True, root_controller=RootController())
     cls.wsgi_app = config.make_wsgi_app()
예제 #50
0
        output += "  Imagem:<br>"
        #output+="  <input type=\"text\" name=\"imagem\"><br>"
        output += "  <input type=\"file\" name=\"file1\"><br>"
        output += "  <input type=\"submit\" value=\"Submit\">"
        output += " </form> "

        return output

    @expose()
    def conteiner(self, numero=None):
        DBSession.add(Conteiner(numero=numero or ''))
        DBSession.commit()
        return "OK"


config = AppConfig(minimal=True, root_controller=RootController())

config.renderers = ['kajiki']
config.serve_static = True
config.paths['static_files'] = 'img'
config['use_sqlalchemy'] = True
config['sqlalchemy.url'] = 'sqlite:///devdata.db'
from tg.util import Bunch
from sqlalchemy.orm import scoped_session, sessionmaker

DBSession = scoped_session(sessionmaker(autoflush=True, autocommit=False))


def init_model(engine):
    DBSession.configure(bind=engine)
    DeclarativeBase.metadata.create_all(
예제 #51
0
            world = db_session.query(World).get(id)
            world.randomNumber = rp()
            worlds.append(world.serialize())
        db_session.commit()
        return json.dumps(worlds)

    @expose("json")
    def queries(self, queries=1):
        num_queries = getQueryNum(queries)
        rp = partial(randint, 1, 10000)
        get = db_session.query(World).get
        worlds = [get(rp()).serialize() for _ in xrange(num_queries)]
        return json.dumps(worlds)


    @expose()
    def fortune(self):
        fortunes = db_session.query(Fortune).all()
        fortunes.append(Fortune(id=0, message="Additional fortune added at request time."))
        fortunes.sort(key=attrgetter("message"))
        for f in fortunes:
            f.message = bleach.clean(f.message)
            template = env.get_template("fortunes.html")
        return template.render(fortunes=fortunes)

config = AppConfig(minimal=True, root_controller=RootController())
config.renderers.append("jinja")

app = config.make_wsgi_app()