• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python config.Config类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twtxt.config.Config的典型用法代码示例。如果您正苦于以下问题:Python Config类的具体用法?Python Config怎么用?Python Config使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Config类的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: quickstart

def quickstart(ctx):
    """Quickstart wizard for setting up twtxt."""
    width = click.get_terminal_size()[0]
    width = width if width <= 79 else 79

    click.secho("twtxt - quickstart", fg="cyan")
    click.secho("==================", fg="cyan")
    click.echo()

    help = "This wizard will generate a basic configuration file for twtxt with all mandatory options set. " \
           "Have a look at the README.rst to get information about the other available options and their meaning."
    click.echo(textwrap.fill(help, width))

    click.echo()
    nick = click.prompt("➤ Please enter your desired nick", default=os.environ.get("USER", ""))
    twtfile = click.prompt("➤ Please enter the desired location for your twtxt file", "~/twtxt.txt", type=click.Path())

    click.echo()
    add_news = click.confirm("➤ Do you want to follow the twtxt news feed?", default=True)

    conf = Config(None)
    conf.create_config(nick, twtfile, add_news)
    open(os.path.expanduser(twtfile), 'a').close()

    click.echo()
    click.echo("✓ Created config file at '{}'.".format(click.format_filename(conf.config_file)))
开发者ID:djmaze,项目名称:twtxt,代码行数:26,代码来源:cli.py


示例2: test_build_default_map

def test_build_default_map():
    empty_cfg = configparser.ConfigParser()
    empty_conf = Config("foobar", empty_cfg)

    default_map = {
        "following": {
            "check": empty_conf.check_following,
            "timeout": empty_conf.timeout,
            "porcelain": empty_conf.porcelain,
        },
        "tweet": {
            "twtfile": empty_conf.twtfile,
        },
        "timeline": {
            "pager": empty_conf.use_pager,
            "cache": empty_conf.use_cache,
            "limit": empty_conf.limit_timeline,
            "timeout": empty_conf.timeout,
            "sorting": empty_conf.sorting,
            "porcelain": empty_conf.porcelain,
            "twtfile": empty_conf.twtfile,
        },
        "view": {
            "pager": empty_conf.use_pager,
            "cache": empty_conf.use_cache,
            "limit": empty_conf.limit_timeline,
            "timeout": empty_conf.timeout,
            "sorting": empty_conf.sorting,
            "porcelain": empty_conf.porcelain,
        }
    }

    assert empty_conf.build_default_map() == default_map
开发者ID:timofurrer,项目名称:twtxt,代码行数:33,代码来源:test_config.py


示例3: test_from_file

def test_from_file(config_dir):
    with pytest.raises(ValueError) as e:
        Config.from_file("invalid")
    assert "Config file not found." in str(e.value)

    with open(str(config_dir.join("empty")), "a") as fh:
        fh.write("XXX")
    with pytest.raises(ValueError) as e:
        Config.from_file(str(config_dir.join("empty")))
    assert "Config file is invalid." in str(e.value)

    conf = Config.from_file(str(config_dir.join(Config.config_name)))
    check_cfg(conf)
开发者ID:timofurrer,项目名称:twtxt,代码行数:13,代码来源:test_config.py


示例4: test_check_config_file_sanity

def test_check_config_file_sanity(capsys, config_dir):
    with pytest.raises(ValueError) as e:
        Config.from_file(str(config_dir.join("config_sanity")))
    assert "Error in config file." in str(e.value)

    out, err = capsys.readouterr()
    for line in ["✗ Config error on limit_timeline - invalid literal for int() with base 10: '2t0'",
                 "✗ Config error on check_following - Not a boolean: TTrue",
                 "✗ Config error on porcelain - Not a boolean: Faltse",
                 "✗ Config error on disclose_identity - Not a boolean: Ftalse",
                 "✗ Config error on timeout - could not convert string to float: '5t.0'",
                 "✗ Config error on use_pager - Not a boolean: Falste",
                 "✗ Config error on use_cache - Not a boolean: Trute"]:
        assert line in out
开发者ID:Creative-Reflex,项目名称:twtxt,代码行数:14,代码来源:test_config.py


示例5: check_if_following

def check_if_following(follower):
    config = Config.discover()

    if config.get_source_by_nick(follower):
        return True

    return False
开发者ID:myles,项目名称:twtxt.mylesb.ca,代码行数:7,代码来源:followers.py


示例6: cli

def cli(ctx, config, verbose):
    """Decentralised, minimalist microblogging service for hackers."""
    init_logging(debug=verbose)

    try:
        if config:
            conf = Config.from_file(config)
        else:
            conf = Config.discover()
    except ValueError:
        click.echo("Error loading config file.")
        if not config:
            if click.confirm("Do you want to run the twtxt quickstart wizard?", abort=True):
                pass

    ctx.default_map = conf.build_default_map()
    ctx.obj = {'conf': conf}
开发者ID:gitter-badger,项目名称:twtxt,代码行数:17,代码来源:cli.py


示例7: test_create_config

def test_create_config(config_dir):
    config_dir_old = Config.config_dir
    Config.config_dir = str(config_dir.join("new"))
    conf_w = Config.create_config("bar", "batz.txt", False, True)
    conf_r = Config.discover()
    assert conf_r.nick == "bar"
    assert conf_r.twtfile == "batz.txt"
    assert conf_r.character_limit == 140
    assert conf_r.following[0].nick == "twtxt"
    assert conf_r.following[0].url == "https://buckket.org/twtxt_news.txt"
    assert set(conf_r.options.keys()) == {"nick", "twtfile", "disclose_identity", "character_limit"}

    conf_r.cfg.remove_section("twtxt")
    assert conf_r.options == {}

    conf_r.cfg.remove_section("following")
    assert conf_r.following == []
    Config.config_dir = config_dir_old
开发者ID:timofurrer,项目名称:twtxt,代码行数:18,代码来源:test_config.py


示例8: cli

def cli(ctx, config, verbose):
    """Decentralised, minimalist microblogging service for hackers."""
    init_logging(debug=verbose)

    if ctx.invoked_subcommand == "quickstart":
        return

    try:
        if config:
            conf = Config.from_file(config)
        else:
            conf = Config.discover()
    except ValueError:
        click.echo("✗ Config file not found or not readable. You may want to run twtxt quickstart.")
        sys.exit()

    ctx.default_map = conf.build_default_map()
    ctx.obj = {'conf': conf}
开发者ID:timofurrer,项目名称:twtxt,代码行数:18,代码来源:cli.py


示例9: cli

def cli(ctx, config, verbose):
    """Decentralised, minimalist microblogging service for hackers."""
    init_logging(debug=verbose)

    if ctx.invoked_subcommand == "quickstart":
        return  # Skip initializing config file

    try:
        if config:
            conf = Config.from_file(config)
        else:
            conf = Config.discover()
    except ValueError as e:
        if "Error in config file." in str(e):
            click.echo("✗ Please correct the errors mentioned above an run twtxt again.")
        else:
            click.echo("✗ Config file not found or not readable. You may want to run twtxt quickstart.")
        sys.exit()

    ctx.default_map = conf.build_default_map()
    ctx.obj = {'conf': conf}
开发者ID:DracoBlue,项目名称:twtxt,代码行数:21,代码来源:cli.py


示例10: quickstart

def quickstart():
    """Quickstart wizard for setting up twtxt."""
    width = click.get_terminal_size()[0]
    width = width if width <= 79 else 79

    click.secho("twtxt - quickstart", fg="cyan")
    click.secho("==================", fg="cyan")
    click.echo()

    help_text = "This wizard will generate a basic configuration file for twtxt with all mandatory options set. " \
                "You can change all of these later with either twtxt itself or by editing the config file manually. " \
                "Have a look at the docs to get information about the other available options and their meaning."
    click.echo(textwrap.fill(help_text, width))

    click.echo()
    nick = click.prompt("➤ Please enter your desired nick", default=os.environ.get("USER", ""))

    def overwrite_check(path):
        if os.path.isfile(path):
            click.confirm("➤ '{0}' already exists. Overwrite?".format(path), abort=True)

    cfgfile = click.prompt("➤ Please enter the desired location for your config file",
                           os.path.join(Config.config_dir, Config.config_name),
                           type=click.Path(readable=True, writable=True, file_okay=True))
    cfgfile = os.path.expanduser(cfgfile)
    overwrite_check(cfgfile)

    twtfile = click.prompt("➤ Please enter the desired location for your twtxt file",
                           os.path.expanduser("~/twtxt.txt"),
                           type=click.Path(readable=True, writable=True, file_okay=True))
    twtfile = os.path.expanduser(twtfile)
    overwrite_check(twtfile)

    twturl = click.prompt("➤ Please enter the URL your twtxt file will be accessible from",
                          default="https://example.org/twtxt.txt")

    disclose_identity = click.confirm("➤ Do you want to disclose your identity? Your nick and URL will be shared when "
                                      "making HTTP requests", default=False)

    click.echo()
    add_news = click.confirm("➤ Do you want to follow the twtxt news feed?", default=True)

    conf = Config.create_config(cfgfile, nick, twtfile, twturl, disclose_identity, add_news)

    twtfile_dir = os.path.dirname(twtfile)
    if not os.path.exists(twtfile_dir):
        os.makedirs(twtfile_dir)
    open(twtfile, "a").close()

    click.echo()
    click.echo("✓ Created config file at '{0}'.".format(click.format_filename(conf.config_file)))
    click.echo("✓ Created twtxt file at '{0}'.".format(click.format_filename(twtfile)))
开发者ID:Creative-Reflex,项目名称:twtxt,代码行数:52,代码来源:cli.py


示例11: test_add_get_remove_source

def test_add_get_remove_source():
    conf = Config.discover()
    conf.cfg.remove_section("following")

    assert conf.remove_source_by_nick("foo") is False
    assert conf.get_source_by_nick("baz") is None

    conf.add_source(Source("foo", "bar"))
    source = conf.get_source_by_nick("foo")
    assert source.nick == "foo"
    assert source.url == "bar"

    assert conf.remove_source_by_nick("baz") is False
    assert conf.remove_source_by_nick("foo") is True
    assert conf.following == []
开发者ID:timofurrer,项目名称:twtxt,代码行数:15,代码来源:test_config.py


示例12: test_discover

def test_discover():
    conf = Config.discover()
    check_cfg(conf)
开发者ID:timofurrer,项目名称:twtxt,代码行数:3,代码来源:test_config.py


示例13: retrieve_file

def retrieve_file(client, source, limit, cache):
    is_cached = cache.is_cached(source.url) if cache else None
    headers = {"If-Modified-Since": cache.last_modified(source.url)} if is_cached else {}

    try:
        response = yield from client.request("get",source.url, headers=headers,allow_redirects=False)
        content = yield from response.text()
    except Exception as e:
        if is_cached:
            logger.debug("{}: {} - using cached content".format(source.url, e))
            return cache.get_tweets(source.url, limit)
    #comp490
        elif e==ssl.CertificateError:

            click.echo("Warning the source: "+source.nick+" is unsafe: Hostname does not match name on SSL certificate")
            return []
        elif e==aiohttp.errors.ClientOSError:

            if "[[SSL: CERTIFICATE_VERIFY_FAILED" in str(e):
                click.echo("Warning the source: "+source.nick+" is unsafe: The ssl certificate has expired")
                return []
            elif "[SSL: EXCESSIVE_MESSAGE_SIZE]" in str(e):
                click.echo("Warning the source: "+source.nick+" is unsafe: source has sent an invalid response")
    #COMP490
        else:
            logger.debug(e)
            return []

    if response.status == 200:
        tweets = parse_tweets(content.splitlines(), source)

        if cache:
            last_modified_header = response.headers.get("Last-Modified")
            if last_modified_header:
                logger.debug("{} returned 200 and Last-Modified header - adding content to cache".format(source.url))
                cache.add_tweets(source.url, last_modified_header, tweets)
            else:
                logger.debug("{} returned 200 but no Last-Modified header - can’t cache content".format(source.url))
        else:
            logger.debug("{} returned 200".format(source.url))

        return sorted(tweets, reverse=True)[:limit]
#comp490
    elif response.status==301:
        cache = Cache.discover()
        conf=Config.discover()
        tweets=cache.get_tweets(source.url)

        conf.remove_source_by_nick(source.nick)
        url=response.headers["Location"]
        conf.add_source(Source(source.nick,url))
        for tweet in tweets:
            cache.add_tweet(url,0,tweet)
#comp490
    elif response.status == 410 and is_cached:
        # 410 Gone:
        # The resource requested is no longer available,
        # and will not be available again.
        logger.debug("{} returned 410 - deleting cached content".format(source.url))
        cache.remove_tweets(source.url)
        return []

    elif is_cached:
        logger.debug("{} returned {} - using cached content".format(source.url, response.status))
        return cache.get_tweets(source.url, limit)

    else:
        logger.debug("{} returned {}".format(source.url, response.status))
        return []
开发者ID:Puddinglord,项目名称:twtxt,代码行数:69,代码来源:twhttp.py



注:本文中的twtxt.config.Config类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python botapi.TelegramBot类代码示例发布时间:2022-05-27
下一篇:
Python twokenize.tokenize函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap