예제 #1
0
 def test_lazy_loading(self):
     model = LazyModel('registry', 'asdfg')
     with self.assertRaises(MissingModelError):
         model._meta
     with self.assertRaises(MissingModelError):
         model._meta = None
     with self.assertRaises(MissingModelError):
         del model._meta
예제 #2
0
 def test_call(self):
     model = LazyModel('registry', 'Entry')
     from yepes.contrib.registry.abstract_models import BaseEntry
     from yepes.contrib.registry.models import Entry
     self.assertIsInstance(model(), BaseEntry)
     self.assertIsInstance(model(), Entry)
     self.assertIsInstance(model(), model)
예제 #3
0
 def test_subclass_check(self):
     model = LazyModel('registry', 'Entry')
     from yepes.contrib.registry.abstract_models import BaseEntry
     from yepes.contrib.registry.models import Entry
     self.assertFalse(issubclass(BaseEntry, Entry))
     self.assertFalse(issubclass(BaseEntry, model))
     self.assertTrue(issubclass(Entry, Entry))
     self.assertTrue(issubclass(Entry, model))
     self.assertTrue(issubclass(model, Entry))
     self.assertTrue(issubclass(model, model))
예제 #4
0
 def test_class(self):
     model = LazyModel('registry', 'Entry')
     from yepes.contrib.registry.abstract_models import BaseEntry
     from yepes.contrib.registry.models import Entry
     self.assertEqual(model.__class__, BaseEntry.__class__)
     self.assertEqual(model.__class__, Entry.__class__)
예제 #5
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

import re

from yepes.loading import LazyModel

Attachment = LazyModel('attachments', 'Attachment')

__all__ = ('attachment_tags', )

TAGS_RE = re.compile(
    r"""
    (?P<open_paragraph><p[^>]*>\s*)?
    \[
        (?P<tag>audio|iframe|image|link|video)
        (?:=(?P<arg>[a-zA-Z0-9]+))?
        (?P<classes>(?:\ +[a-zA-Z0-9_\-]+)+)?
        (?:\ +\#(?P<id>[a-zA-Z0-9_\-]+))?
        (?P<attributes>(?:\ +[a-zA-Z]+=(?:[a-zA-Z0-9_\-]+|'[^']*'|"[^"]*"))+)?
    \]
    (?P<content>[^[\]]+)
    \[
        /
        \2
    \]
    (?P<close_paragraph>\s*</p>)?
""", re.VERBOSE)

예제 #6
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.utils import timezone

from yepes.loading import LazyModel

Delivery = LazyModel('newsletters', 'Delivery')


def message_bounced(sender, instance, created, **kwargs):
    if created:
        Delivery.objects.filter(
            message=instance.message_id,
            subscriber=instance.subscriber_id,
            is_bounced=False,
        ).update(is_bounced=True, bounce_date=timezone.now())


def message_clicked(sender, instance, created, **kwargs):
    if created:
        now = timezone.now()
        Delivery.objects.filter(
            message=instance.message_id,
            subscriber=instance.subscriber_id,
            is_clicked=False,
        ).update(is_clicked=True, click_date=now)
        Delivery.objects.filter(         # Subscribers
            message=instance.message_id,          # cannot click
            subscriber=instance.subscriber_id,    # on links without
예제 #7
0
from yepes.model_mixins import (
    Enableable,
    Illustrated,
    Logged,
    MetaData,
    Orderable,
    Slugged,
)
from yepes.utils.emails import normalize_email, validate_email
from yepes.utils.html import extract_text
from yepes.utils.properties import described_property
from yepes.validators.email import DOMAIN_RE

NewsletterManager = apps.get_class('newsletters.managers', 'NewsletterManager')

Delivery = LazyModel('newsletters', 'Delivery')
Domain = LazyModel('newsletters', 'Domain')


class AbstractBounce(models.Model):

    message = models.ForeignKey('Message',
                                on_delete=models.CASCADE,
                                related_name='bounces',
                                verbose_name=_('Message'))
    newsletter = models.ForeignKey('Newsletter',
                                   on_delete=models.CASCADE,
                                   related_name='bounces',
                                   verbose_name=_('Newsletter'))
    subscriber = models.ForeignKey('Subscriber',
                                   null=True,
예제 #8
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.contrib.sites.managers import CurrentSiteManager
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.formats import date_format
from django.utils.translation import ugettext_lazy as _

from yepes import fields
from yepes.apps import apps
from yepes.loading import LazyModel
from yepes.types import Undefined

Page = LazyModel('metrics', 'Page')
Parameter = apps.get_class('metrics.model_mixins', 'Parameter')

CountryField = apps.get_class('standards.fields', 'CountryField')
LanguageField = apps.get_class('standards.fields', 'LanguageField')
RegionField = apps.get_class('standards.fields', 'RegionField')


class AbstractBrowser(Parameter):
    class Meta:
        abstract = True
        ordering = ['index']
        verbose_name = _('Browser')
        verbose_name_plural = _('Browsers')

예제 #9
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.utils.encoding import python_2_unicode_compatible

from yepes.loading import LazyModel

Configuration = LazyModel('thumbnails', 'Configuration')


@python_2_unicode_compatible
class ConfigurationProxy(object):
    def __init__(self, width, height, **kwargs):
        self._wrapped = Configuration(width=width, height=height, **kwargs)

        tokens = []
        if self._wrapped.width:
            tokens.append('w{0}'.format(self._wrapped.width))

        if self._wrapped.height:
            tokens.append('h{0}'.format(self._wrapped.height))

        if self._wrapped.background:
            tokens.append('b{0}'.format(
                self._wrapped.background.lstrip('#').upper()))

        if self._wrapped.mode != 'limit':
            tokens.append('m{0}'.format(self._wrapped.mode.upper()))

        if self._wrapped.algorithm != 'undefined':
예제 #10
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.utils.text import Truncator

from yepes.contrib.registry import registry
from yepes.loading import LazyClass, LazyModel
from yepes.utils.http import get_meta_data

Comment = LazyModel('comments', 'Comment')
CommentForm = LazyClass('comments.forms', 'CommentForm')


class CommentHandler(object):

    # PUBLIC METHODS

    @classmethod
    def create_comment(cls, post, data, request):

        if not post.allow_comments():
            return None

        author = cls._get_author(request)
        name = data['author_name']
        email = data['author_email']
        url = data['author_url']
        ip_address = cls._get_ip_address(request)
        user_agent = cls._get_user_agent(request)
        referer = cls._get_referer(request)
예제 #11
0
from django.core.files.base import ContentFile, File
from django.core.files.storage import default_storage
from django.db.models.fields.files import FieldFile
from django.utils import six
from django.utils import timezone
from django.utils.encoding import force_bytes

from yepes.conf import settings
from yepes.contrib.thumbnails import engine
from yepes.contrib.thumbnails.utils import clean_config
from yepes.loading import LazyModel
from yepes.types import Undefined
from yepes.utils.html import make_single_tag

Source = LazyModel('thumbnails', 'source')


class ImageFile(File):

    _format_cache = None
    _height_cache = None
    _image_cache = None
    _width_cache = None

    def __del__(self):
        self.close()

    def _del_image(self, source):
        self._image_cache = None
        self._format_cache = None
예제 #12
0
from django.utils import six
from django.utils.encoding import force_bytes, force_text

from yepes.contrib.registry.utils import get_site
from yepes.loading import LazyModel

__all__ = (
    'AlreadyRegisteredError',
    'InvalidFieldError',
    'InvalidKeyError',
    'UnregisteredError',
    'Registry',
    'registry',
    'REGISTRY_KEYS',
)
Entry = LazyModel('registry', 'Entry')
LongEntry = LazyModel('registry', 'LongEntry')

KEY_RE = re.compile(r'^[a-zA-Z][a-zA-Z_-]*[a-zA-Z]$')
REGISTRY_KEYS = {}


class AlreadyRegisteredError(KeyError):
    def __init__(self, key):
        msg = "Key '{0!s}' is already registered."
        super(AlreadyRegisteredError, self).__init__(msg.format(key))
        self.key = key


class InvalidFieldError(ValueError):
    def __init__(self, field):
예제 #13
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.utils import six

from yepes.contrib.datamigrations import BaseModelMigration, TextField
from yepes.loading import LazyClass, LazyModel
from yepes.utils.properties import cached_property

Subscriber = LazyModel('newsletters', 'Subscriber')
SubscriberPlan = LazyClass('newsletters.importation_plans', 'SubscriberPlan')


class SubscriberImportation(BaseModelMigration):

    can_create = True
    can_export = False
    can_update = False

    fields = [
        TextField('email_address'),
        TextField('first_name'),
        TextField('last_name'),
        TextField('newsletters'),
        TextField('tags'),
    ]

    def __init__(self):
        super(SubscriberImportation, self).__init__(Subscriber)
예제 #14
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

import re

from django.template import Context, Template

from yepes.loading import LazyModel

MessageImage = LazyModel('newsletters', 'MessageImage')
MessageLink = LazyModel('newsletters', 'MessageLink')

IMAGE_RE = re.compile(r"\{% image_url '([^']*)' %\}")
LINK_RE = re.compile(r"\{% link_url '([^']*)' %\}")


def prerender(source, context=None):
    ctxt = Context({'prerendering': True})
    load = '{% load newsletters %}\n'
    if context is not None:
        ctxt.update(context)

    prerendered = Template(load + source).render(ctxt)

    image_names = set()

    def image_collector(matchobj):
        image_names.add(matchobj.group(1))
        return matchobj.group(0)
예제 #15
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from yepes.contrib.datamigrations.importation_plans import ModelImportationPlan
from yepes.loading import LazyModel
from yepes.utils.emails import normalize_email, validate_email

Domain = LazyModel('newsletters', 'Domain')
Newsletter = LazyModel('newsletters', 'Newsletter')
SubscriberTag = LazyModel('newsletters', 'SubscriberTag')


class SubscriberPlan(ModelImportationPlan):

    updates_data = False

    def import_batch(self, batch):
        model = self.migration.model
        key = self.migration.primary_key.attname
        existing_keys = self.get_existing_keys(batch)
        for row in batch:
            if row[key] in existing_keys:
                continue

            address = normalize_email(row['email_address'])
            if not validate_email(address):
                msg = "'{0}' is not a valid email address."
                raise ValueError(msg.format(address))

            _, domain_name = address.rsplit('@', 1)
예제 #16
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.core.management.base import BaseCommand

from yepes.loading import LazyModel

Post = LazyModel('posts', 'Post')
PostRecord = LazyModel('posts', 'PostRecord')


class Command(BaseCommand):
    help = 'Collects the statistics of the posts and calculates their score.'
    requires_system_checks = True

    def handle(self, **options):
        PostRecord.objects.calculate_stats()
        PostRecord.objects.calculate_score()
        Post.objects.update_stats()
        verbosity = int(options.get('verbosity', '1'))
        if verbosity > 0:
            self.stdout.write('Stats were successfully updated.')

예제 #17
0
 def test_instance_check(self):
     model = LazyModel('registry', 'Entry')
     from yepes.contrib.registry.models import Entry
     self.assertIsInstance(Entry(), model)
     self.assertIsInstance(model(), model)
예제 #18
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from django.forms.fields import CharField, IntegerField
from django.forms.forms import Form as BaseForm
from django.forms.models import BaseModelFormSet
from django.forms.widgets import HiddenInput

from yepes.contrib.registry import registry, REGISTRY_KEYS
from yepes.contrib.registry.models import Entry
from yepes.loading import LazyModel
from yepes.utils.properties import cached_property

Site = LazyModel('sites', 'Site')


class EntryFormSet(BaseModelFormSet):

    absolute_max = 1000
    can_delete = False
    can_order = False
    extra=0
    form = None
    max_num = None
    model = Entry
    validate_max = False

    def _construct_form(self, entry, **kwargs):
        value_field = REGISTRY_KEYS[entry.key]
        value_field.initial = entry.value
예제 #19
0
 def test_representation(self):
     model = LazyModel('registry', 'Entry')
     self.assertEqual(repr(model), '<LazyModel: registry.Entry>')
     model = LazyModel('registry', 'asdfg')
     self.assertEqual(repr(model), '<LazyModel: registry.asdfg>')
예제 #20
0
# -*- coding:utf-8 -*-

from __future__ import unicode_literals

from functools import update_wrapper

from django.conf.urls import url
from django.utils.http import urlencode

from yepes import admin
from yepes.loading import LazyModel

Blog = LazyModel('blogs', 'Blog')


class BlogModelAdmin(admin.ModelAdmin):

    blog_field = 'blog'

    def formfield_for_dbfield(self, db_field, **kwargs):
        formfield = super(BlogModelAdmin,
                          self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == 'blog':
            user = kwargs['request'].user
            blogs = Blog.objects.filter(authors=user)
            try:
                formfield.initial = blogs[0]
            except IndexError:
                pass
        return formfield