Пример #1
0
def filter_field(key, fields, func=None):
    """
    Run a field through the given filter, or default if none is provided. If
    field doesn't exist, it will attempt to return the default value for that
    field.

    :param key: the field name to use
    :param fields: a dictionary of available fields in the form ``name: value``
    :returns: Filtered value
    :raises: KeyError in the event the field can't be found among the provided
        ones or the defaults
    """
    try:
        val = fields[key]
    except KeyError:
        default_fields = getattr(settings, 'PUBLISH_FIELD_DEFAULTS', {})
        FIELD_DEFAULTS.update(default_fields)
        try:
            val = FIELD_DEFAULTS[key]
        except KeyError:
            raise ConfigurationError('You must supply the `%s` field in the'
                            ' article, via settings.PUBLISH_FIELD_DEFAULTS, or'
                            ' via command line (where applicable)' % key)


    default_filters = getattr(settings, 'PUBLISH_FILTER_DEFAULTS', {})
    FILTER_DEFAULTS.update(default_filters)
    f = func or FILTER_DEFAULTS[key] 
    return f(val)
Пример #2
0
def publish(f, draft, by=None, publish=None, is_active=True, login_required=False, debug=False):
    """
    Publishes an article.

    :param f: The file to parse
    :type f: file
    :param by: Author username
    :type by: str
    :param draft: Save as draft?
    :type draft: bool
    :param draft: Article active?
    :type draft: bool
    :param draft: Require login?
    :type draft: bool
    :param publish: When to publish
    :type publish: datetime fmt=YYYY-MM-DD HH:MM
    :param debug: Print debug data
    :type debug: bool

    :returns: Saved :class:`Article`
    """
    meta, content = parse_meta_and_article(f.read())
    meta.update({
        'is_active': is_active,
        'login_required': login_required,
    })
    if draft:
        meta['status'] = 'Draft'
    if publish:
        meta['publish'] = publish
    if by:
        meta['by'] = by
    slug = slugify(meta['title'])
    # New or updated?
    articles = Article.objects.using(DB).filter(slug=slug)
    if len(articles) > 1:
        if not publish:
            raise ConfigurationError('Title ambiguous; supply publish date')
        articles.filter(publish_date=meta['publish'])
        article = articles[0]
    elif len(articles) == 1:
        article = articles[0]
    else:
        article = Article()

    article.content = content
    article.markup = 'h'

    todo = []
    keys = list(meta.keys())
    for key in keys + [k for k in REQUIRED_FIELDS+FIELD_DEFAULTS.keys() if k not in keys]:
        value = filter_field(key, meta)
        if key not in SAVE_NEEDED:
            setfield(article, key, value, debug)
        else:
            todo.append((key, value))
    article.save(using=DB)

    for key, value in todo:
        setfield(article, key, value, debug)
    article.save(using=DB)

    return article