Exemplo n.º 1
0
def test_ashes():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.html'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/<name>/', hello_world_ctx, tmpl),
                       ('/beta/<name>/', complex_context, tmpl)],
                      render_factory=ashes_render)

    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'world' in resp.data

    resp = c.get('/beta/Rajkumar/')
    assert resp.status_code, 200
    assert b'Rajkumar' in resp.data

    # test rebind

    # no loss of binding on applications with no render factory
    wrap_app = Application([('/', app)])
    assert wrap_app.routes[0].render_factory is ashes_render
    c = wrap_app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'<html>' in resp.data
    assert b'world' in resp.data

    # test bind new but not old
    ashes_render2 = AshesRenderFactory(_TMPL_DIR)
    wrap_app2 = Application([('/test', hello_world_ctx, tmpl), ('/', app)],
                            render_factory=ashes_render2)
    assert wrap_app2.routes[0].render_factory is ashes_render2
    assert wrap_app2.routes[1].render_factory is ashes_render
Exemplo n.º 2
0
def test_ashes_missing_template():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'missing_template.html'
    with raises(ashes.TemplateNotFound):
        return Application([('/', hello_world_ctx, tmpl)],
                           render_factory=ashes_render)
    return
Exemplo n.º 3
0
def create_app():
    routes = [('/', top, 'top.html'),
              ('/clastic_assets/', StaticApplication(_ASSET_PATH)),
              ('/json/', top, render_json)]
    arf = AshesRenderFactory(_CUR_PATH)
    app = Application(routes, {}, arf)
    return app
Exemplo n.º 4
0
def create_app():
    static_app = StaticApplication(STATIC_PATH)
    routes = [
        ("/", home, "home.html"),
        ("/show", show_time, render_json),
        ("/static", static_app),
    ]
    render_factory = AshesRenderFactory(CUR_PATH)
    return Application(routes, render_factory=render_factory)
Exemplo n.º 5
0
def create_app():
    pdm = PostDataMiddleware(['lang', 'list_id', 'subject', 'intro', 'send_key', 'is_dev'])
    ma = MetaApplication()
    routes = [('/', ma),
              #('/meta', ma),
              ('/_dump_environ', lambda request: request.environ, render_basic),
              ('/bake', bake_latest_issue, render_basic),
              ('/archive/<lang>', get_archive, render_basic),
              ('/build_archives', render_and_save_archives, render_basic),
              ('/view', get_language_list, render_basic),
              ('/view/<lang>/<format?>', get_rendered_issue, render_basic),
              ('/fetch/', fetch_rc, render_json),
              ('/fetch/<lang>', fetch_rc, render_json),
              ('/publish/', get_control_info, 'controls.html'),
              POST('/publish/send', send_issue, render_basic,
                   middlewares=[pdm]),
              ('/static', StaticApplication(STATIC_PATH))]
    site_rf = AshesRenderFactory(SITE_TEMPLATES_PATH)
    issue_rf = AshesRenderFactory(ISSUE_TEMPLATES_PATH,
                                  filters={'ci': comma_int})
    resources = {'issue_ashes_env': issue_rf.env}
    return Application(routes, resources,
                       render_factory=site_rf)
Exemplo n.º 6
0
def test_ashes_mixed():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.html'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/json/', hello_world_ctx, render_basic)],
                      render_factory=ashes_render)

    c = Client(app, BaseResponse)
    resp = c.get('/')
    yield eq_, resp.status_code, 200
    yield ok_, 'Salam' in resp.data

    resp = c.get('/json/')
    yield eq_, resp.status_code, 200
Exemplo n.º 7
0
def test_ashes_mixed():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.html'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/json/', hello_world_ctx, render_basic)],
                      render_factory=ashes_render)

    c = app.get_local_client()
    resp = c.get('/')
    assert resp.status_code == 200
    assert b'Salam' in resp.data

    resp = c.get('/json/')
    assert resp.status_code == 200
Exemplo n.º 8
0
def test_ashes():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'basic_template.html'
    app = Application([('/', hello_world_ctx, tmpl),
                       ('/<name>/', hello_world_ctx, tmpl),
                       ('/beta/<name>/', complex_context, tmpl)],
                      render_factory=ashes_render)

    c = Client(app, BaseResponse)
    resp = c.get('/')
    yield eq_, resp.status_code, 200
    yield ok_, 'world' in resp.data

    resp = c.get('/beta/Rajkumar/')
    yield eq_, resp.status_code, 200
    yield ok_, 'Rajkumar' in resp.data
Exemplo n.º 9
0
def create_app():
    _template_dir = os.path.join(_CUR_PATH, TEMPLATES_PATH)
    _static_dir = os.path.join(_CUR_PATH, STATIC_PATH)
    templater = AshesRenderFactory(_template_dir)
    # TODO: Add support for @mentions
    routes = [('/', home, 'index.html'), ('/docs', home, 'docs.html'),
              ('/tags/<limit>', generate_tag_list, render_basic),
              ('/search/', generate_report, 'report.html'),
              ('/search/all', generate_report, 'report.html'),
              ('/search/all/<offset>', generate_report, 'report.html'),
              ('/search/<tag>', generate_report, 'report.html'),
              ('/csv/<tag>', generate_csv, render_basic),
              ('/search/<tag>/<offset>', generate_report, 'report.html'),
              ('/logs', generate_run_log, 'logs.html'),
              ('/logs/<lang>', generate_lang_run_log, 'lang_logs.html'),
              ('/static', StaticApplication(_static_dir)),
              ('/meta/', MetaApplication())]
    return Application(routes, middlewares=[], render_factory=templater)
Exemplo n.º 10
0
def create_app(link_list_path=None,
               local_root=None,
               host_url=None,
               secret_key=None):
    link_list_path = link_list_path or _DEFAULT_LINKS_FILE_PATH
    link_map = LinkMap(link_list_path)
    local_static_app = None
    if local_root:
        local_static_app = StaticApplication(local_root)
    host_url = (host_url or 'localhost:5000').rstrip('/') + '/'
    full_host_url = 'http://' + host_url
    resources = {
        'link_map': link_map,
        'local_root': local_root,
        'local_static_app': local_static_app,
        'host_url': host_url,
        'full_host_url': full_host_url
    }

    pdm = PostDataMiddleware({
        'target_url': unicode,
        'target_file': unicode,
        'alias': unicode,
        'max_count': int,
        'expiry_time': unicode
    })
    submit_route = POST('/submit',
                        add_entry,
                        add_entry_render,
                        middlewares=[pdm])

    routes = [('/', home, 'home.html'), submit_route, ('/<alias>', use_entry)]
    scm = SignedCookieMiddleware(secret_key=secret_key)
    scp = SimpleContextProcessor('local_root', 'full_host_url')
    middlewares = [scm, scp]

    arf = AshesRenderFactory(_CUR_PATH, keep_whitespace=False)
    app = Application(routes, resources, middlewares, arf)
    return app
Exemplo n.º 11
0
def create_app():
    new_link_mw = PostDataMiddleware({
        "target_url": str,
        "new_alias": str,
        "expiry_time": int,
        "max_count": int
    })

    static_app = StaticApplication(STATIC_PATH)
    routes = [
        ("/", home, "home.html"),
        POST("/submit", add_entry, middlewares=[new_link_mw]),
        ("/static", static_app),
        GET("/<alias>", use_entry),
    ]

    config_path = os.path.join(CUR_PATH, "erosion.ini")
    config = ConfigParser()
    config.read(config_path)

    host_url = config["erosion"]["host_url"].rstrip("/") + "/"
    db_path = config["erosion"]["db_path"]
    if not os.path.isabs(db_path):
        db_path = os.path.join(os.path.dirname(config_path), db_path)
    resources = {"host_url": host_url, "db": LinkDB(db_path)}

    cookie_secret = config["erosion"]["cookie_secret"]
    cookie_mw = SignedCookieMiddleware(secret_key=cookie_secret)

    render_factory = AshesRenderFactory(CUR_PATH)
    return Application(
        routes,
        resources=resources,
        middlewares=[cookie_mw],
        render_factory=render_factory,
    )
Exemplo n.º 12
0
def create_app(env_name='prod'):
    # rendering is handled by MessageMiddleware
    ui_routes = (PUBLIC_UI_ROUTES + JUROR_UI_ROUTES + ADMIN_UI_ROUTES +
                 META_UI_ROUTES)
    api_routes = (PUBLIC_API_ROUTES + JUROR_API_ROUTES + ADMIN_API_ROUTES +
                  META_API_ROUTES)
    print '==  creating WSGI app using env name: %s' % (env_name, )

    config_file_name = 'config.%s.yaml' % env_name
    config_file_path = os.path.join(PROJ_PATH, config_file_name)

    print '==  loading config file: %s' % (config_file_path, )

    config = yaml.load(open(config_file_path))

    logging.basicConfig()
    logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN)

    engine = create_engine(config.get('db_url', DEFAULT_DB_URL),
                           pool_recycle=60)
    session_type = sessionmaker()
    session_type.configure(bind=engine)
    tmp_rdb_session = session_type()

    schema_errors = get_schema_errors(Base, tmp_rdb_session)
    if not schema_errors:
        print '++  schema validated ok'
    else:
        for err in schema_errors:
            print '!! ', err
        print '!!  recreate the database and update the code, then try again'
        sys.exit(2)

    # create maintainer users if they don't exist yet
    musers = bootstrap_maintainers(tmp_rdb_session)
    if musers:
        print '++ created new users for maintainers: %r' % (musers, )

    new_series = ensure_series(tmp_rdb_session)
    if new_series:
        print '++ created new series: %r' % new_series

    tmp_rdb_session.commit()

    engine.echo = config.get('db_echo', False)

    if not config.get('db_disable_ping'):
        event.listen(engine, 'engine_connect', ping_connection)

    renderer = AshesRenderFactory(TEMPLATES_PATH)

    cookie_secret = config['cookie_secret']
    assert cookie_secret

    root_path = config.get('root_path', '/')

    scm_secure = env_name == 'prod'  # https only in prod
    scm_mw = SignedCookieMiddleware(secret_key=cookie_secret,
                                    path=root_path,
                                    http_only=True,
                                    secure=scm_secure)
    if not scm_secure:
        scm_mw.data_expiry = NEVER

    def get_engine():
        engine = create_engine(config.get('db_url', DEFAULT_DB_URL),
                               pool_recycle=60)
        engine.echo = config.get('db_echo', False)
        if not config.get('db_disable_ping'):
            event.listen(engine, 'engine_connect', ping_connection)
        return engine

    blank_session_type = sessionmaker()

    middlewares = [
        TimingMiddleware(), scm_mw,
        DBSessionMiddleware(blank_session_type, get_engine),
        UserMiddleware()
    ]
    api_log_path = config.get('api_log_path')
    if api_log_path:
        log_mw = LoggingMiddleware(api_log_path)
        middlewares.insert(0, log_mw)
        # hack
        config['api_exc_log_path'] = getattr(log_mw, 'exc_log_path', None)

    replay_log_path = config.get('replay_log_path')
    if replay_log_path:
        replay_log_mw = ReplayLogMiddleware(replay_log_path)
        middlewares.append(replay_log_mw)

    consumer_token = ConsumerToken(config['oauth_consumer_token'],
                                   config['oauth_secret_token'])

    resources = {
        'config': config,
        'consumer_token': consumer_token,
        'root_path': root_path,
        'ashes_renderer': renderer
    }

    api_app = Application(api_routes,
                          resources,
                          middlewares=[MessageMiddleware()] + middlewares,
                          render_factory=render_basic)
    ui_app = Application(ui_routes,
                         resources,
                         middlewares=[MessageMiddleware(use_ashes=True)] +
                         middlewares,
                         render_factory=renderer)

    static_app = StaticApplication(STATIC_PATH)

    root_app = Application([
        StaticFileRoute('/', STATIC_PATH + '/index.html'), ('/', static_app),
        ('/', ui_app), ('/v1/', api_app), ('/meta', MetaApplication())
    ])

    return root_app
Exemplo n.º 13
0
def send_issue(lang, is_dev=False):
    if is_dev:
        list_id = DEBUG_LIST_ID
    else:
        list_id = LIST_ID_MAP[lang]
    cur_issue = Issue(lang, include_dev=is_dev)
    return cur_issue.send(list_id, SENDKEY)

def get_argparser():
    desc = 'Bake and send Weeklypedia issues. (Please fetch first)'
    prs = ArgumentParser(description=desc)
    prs.add_argument('--lang', default=None)
    prs.add_argument('--bake_all', default=False, action='store_true')
    prs.add_argument('--debug', default=DEBUG, action='store_true')
    return prs


if __name__ == '__main__':
    issue_ashes_env = AshesRenderFactory(ISSUE_TEMPLATES_PATH,
                                         filters={'ci': comma_int}).env
    parser = get_argparser()
    args = parser.parse_args()
    debug = args.debug
    if args.bake_all:
        for lang in SUPPORTED_LANGS:
            bake_latest_issue(issue_ashes_env, lang=lang, include_dev=debug)
    if args.lang in SUPPORTED_LANGS:
        lang = args.lang
        print bake_latest_issue(issue_ashes_env, lang=lang, include_dev=debug)
        print send_issue(lang, debug)
Exemplo n.º 14
0
def create_app():
    routes = [('/', top, 'top.html'), ('/clastic_assets/', META_ASSETS_APP),
              ('/json/', top, render_json)]
    arf = AshesRenderFactory(_CUR_PATH)
    app = Application(routes, render_factory=arf)
    return app
Exemplo n.º 15
0
def create_app(env_name='prod', config=None):
    # rendering is handled by MessageMiddleware
    ui_routes = (PUBLIC_UI_ROUTES + JUROR_UI_ROUTES + ADMIN_UI_ROUTES +
                 META_UI_ROUTES)
    api_routes = (PUBLIC_API_ROUTES + JUROR_API_ROUTES + ADMIN_API_ROUTES +
                  META_API_ROUTES)
    print '==  creating WSGI app using env name: %s' % (env_name, )

    logging.basicConfig()
    logging.getLogger('sqlalchemy.engine').setLevel(logging.WARN)

    if config is None:
        config = load_env_config(env_name=env_name)
    print '==  loaded config file: %s' % (config['__file__'], )

    engine = create_engine(config.get('db_url', DEFAULT_DB_URL),
                           pool_recycle=60)
    session_type = sessionmaker()
    session_type.configure(bind=engine)
    tmp_rdb_session = session_type()

    schema_errors = get_schema_errors(Base, tmp_rdb_session)
    if not schema_errors:
        print '++  schema validated ok'
    else:
        for err in schema_errors:
            print '!! ', err
        print '!!  recreate the database and update the code, then try again'
        sys.exit(2)

    # create maintainer users if they don't exist yet
    musers = bootstrap_maintainers(tmp_rdb_session)
    if musers:
        print '++ created new users for maintainers: %r' % (musers, )

    new_series = ensure_series(tmp_rdb_session)
    if new_series:
        print '++ created new series: %r' % new_series

    tmp_rdb_session.commit()

    engine.echo = config.get('db_echo', False)

    if not config.get('db_disable_ping'):
        event.listen(engine, 'engine_connect', ping_connection)

    renderer = AshesRenderFactory(TEMPLATES_PATH)

    cookie_secret = config['cookie_secret']
    assert cookie_secret

    root_path = config.get('root_path', '/')

    scm_secure = env_name == 'prod'  # https only in prod
    scm_mw = SignedCookieMiddleware(secret_key=cookie_secret,
                                    path=root_path,
                                    http_only=True,
                                    secure=scm_secure)
    if not scm_secure:
        scm_mw.data_expiry = NEVER

    def get_engine():
        engine = create_engine(config.get('db_url', DEFAULT_DB_URL),
                               pool_recycle=60)
        engine.echo = config.get('db_echo', False)
        if not config.get('db_disable_ping'):
            event.listen(engine, 'engine_connect', ping_connection)
        return engine

    blank_session_type = sessionmaker()

    middlewares = [
        TimingMiddleware(),
        UserIPMiddleware(), scm_mw,
        DBSessionMiddleware(blank_session_type, get_engine),
        UserMiddleware()
    ]
    api_log_path = config.get('api_log_path', 'montage_api.log')
    if api_log_path:
        log_mw = LoggingMiddleware(api_log_path)
        middlewares.insert(0, log_mw)
        # hack
        config['api_exc_log_path'] = getattr(log_mw, 'exc_log_path', None)

    replay_log_path = config.get('replay_log_path')
    if replay_log_path:
        replay_log_mw = ReplayLogMiddleware(replay_log_path)
        middlewares.append(replay_log_mw)

    consumer_token = ConsumerToken(config['oauth_consumer_token'],
                                   config['oauth_secret_token'])

    resources = {
        'config': config,
        'consumer_token': consumer_token,
        'root_path': root_path,
        'ashes_renderer': renderer
    }

    debug_errors = bool(os.getenv('MONTAGE_PDB',
                                  False)) or config['__env__'] == 'devtest'
    api_app = Application(
        api_routes,
        resources,
        middlewares=[MessageMiddleware(debug_errors=debug_errors)] +
        middlewares,
        render_factory=render_basic)
    ui_app = Application(
        ui_routes,
        resources,
        middlewares=[
            MessageMiddleware(debug_errors=debug_errors, use_ashes=True)
        ] + middlewares,
        render_factory=renderer)

    static_app = StaticApplication(STATIC_PATH)

    root_mws = [HTTPCacheMiddleware(use_etags=True)]
    if not debug_errors:
        # don't need sentry if you've got pdb, etc.
        sentry_sdk.init(
            environment=config['__env__'],
            request_bodies='medium',
            dsn="https://[email protected]/3532775")
        root_mws.append(SentryMiddleware())

    root_app = Application([
        StaticFileRoute('/', STATIC_PATH + '/index.html'),
        StaticFileRoute('/a/', STATIC_PATH + '/a/index.html'),
        ('/', static_app), ('/', ui_app), ('/v1/', api_app),
        ('/meta', MetaApplication())
    ],
                           resources={'config': config},
                           middlewares=root_mws)

    return root_app
Exemplo n.º 16
0
def test_ashes_missing_template():
    ashes_render = AshesRenderFactory(_TMPL_DIR)
    tmpl = 'missing_template.html'
    return Application([('/', hello_world_ctx, tmpl)],
                       render_factory=ashes_render)
Exemplo n.º 17
0
            d[col[0]] = row[idx]
        return d


def _add_test_data(the_list, count=6):
    for i in range(count):
        is_done = (i % 2) == 1
        the_list.add_task('task_%s' % i, done=is_done)
    return


the_list = TodoList('todo.db')
the_list.create_db(reset=True)
_add_test_data(the_list)

app = Cline(resources={'todo_list': the_list})
ashes_rf = AshesRenderFactory(_CUR_DIR)
done_mw = GetParamMiddleware({'done': int})


@app.route('/', render=ashes_rf('todo.html'), middlewares=[done_mw])
@app.route('/api/todo', middlewares=[done_mw])
def get_tasks(todo_list, done=None):
    tasks = todo_list.get_tasks(done=done)
    print tasks
    return {'tasks': tasks}


if __name__ == '__main__':
    app.run()