示例#1
0
class Click(db.Model, AutoInitModelMixin):
    url_id = db.Column(db.Integer, db.ForeignKey('shorturl.id'))
    user_agent = db.Column(db.String(255), default='Unknown')
    time = db.Column(db.DateTime, default=datetime.now)

    @cached_property
    def url(self):
        return ShortURL.query.filter_by(id=self.url_id).one()

    def __repr__(self):
        return "<Click on '%s'>" % self.url.long_url
示例#2
0
class Link(db.Model):
    __tablename__ = 'links'
    id = db.Column(db.String, primary_key=True)
    url = db.Column(db.String, unique=True, nullable=False)

    def to_json(self):
        return {
            'id': self.id,
            'original_url': self.url,
            'short_url': url_for('shortener.link', id=self.id, _external=True),
            'api_url': url_for('shortener.api_link',
                               id=self.id,
                               _external=True),
        }
示例#3
0
class AutoInitModelMixin(object):
    """
    Mixin for populating models' columns automatically (no need to
    define an __init__ method) and set the default value if any.
    Also sets the model's id and __tablename__ automatically.
    """
    id = db.Column(db.Integer, primary_key=True)

    # use the lowercased class name as the __tablename__
    @declared_attr
    def __tablename__(cls):
        return cls.__name__.lower()

    def __init__(self, *args, **kwargs):
        for attr in (a for a in dir(self) if not a.startswith('_')):
            attr_obj = getattr(self, attr)
            if isinstance(attr_obj, db.Column):
                if attr in kwargs:
                    setattr(self, attr, kwargs[attr])
                else:
                    if hasattr(attr_obj, 'default'):
                        if callable(attr_obj.default):
                            setattr(self, attr, attr_obj.default())
                        else:
                            setattr(self, attr, attr_obj.default)
示例#4
0
class User(db.Model):
    __tablename__ = "users"

    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    username = db.Column(db.String)
    password = db.Column(db.String)  # TO-DO: Add arg `null=False`
    created_at = db.Column(db.BigInteger, default=unix_time)
    api_key = db.Column(db.String)

    # Index
    _idx_username = db.Index("idx_username", "username", unique=True)
    _idx_api_key = db.Index("idx_api_key", "api_key", unique=True)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._urls = set()

    def __repr__(self):
        return "{}:{}".format(self.username, self.id)
示例#5
0
class Link(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    original_url = db.Column(db.String(512))
    short_url = db.Column(db.String(32), unique=True)
    visits = db.Column(db.Integer, default=0)
    date_created = db.Column(db.DateTime, default=datetime.datetime.now())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.short_url = self.generate_short_link()

    def generate_short_link(self):
        characters = string.digits + string.ascii_letters
        short_url = ''.join(choices(characters, k=5))

        link = self.query.filter_by(short_url=short_url).first()

        if link:
            return self.generate_short_link()

        return short_url
示例#6
0
class URL(db.Model):
    """URL Model description"""

    id = db.Column(db.Integer, primary_key=True)
    original_url = db.Column(db.String(512))
    shortened_url = db.Column(db.String(5), unique=True)
    created_at = db.Column(db.DateTime, default=datetime.today())
    expire_in = db.Column(db.Integer, default=90)

    def __init__(self,
                 original_url,
                 expire_in,
                 shortened_url=None,
                 created_at=None):
        self.original_url = original_url
        self.created_at = datetime.today()
        if expire_in is None:
            self.expire_in = 90
        else:
            self.expire_in = expire_in
        self.shortened_url = self.generate_short_url()

    def generate_short_url(self):
        """Generates shortend url part"""

        # URL-allowed characters
        characters = string.digits + string.ascii_letters + "$-_.+!*'(),"

        # Random string of URL-allowed characters of length 5
        # Quantity of available variations of random strings would be
        # 2706784157 (77^5)
        shortened_url = "".join(choices(characters, k=5))

        # Returns True if such random string already exists
        exists = self.query.filter_by(shortened_url=shortened_url).first()

        if exists:
            pass
        return shortened_url
示例#7
0
class Url(db.Model):
    __tablename__ = "urls"
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    url_alias = db.Column(db.String)
    actual_url = db.Column(db.String)
    created_at = db.Column(db.BigInteger, default=unix_time)
    updated_at = db.Column(db.BigInteger, onupdate=unix_time)
    owner_id = db.Column(db.BigInteger, db.ForeignKey("users.id"))

    # Index
    _idx_url_alias = db.Index("idx_url_alias", "url_alias", unique=True)
示例#8
0
class Hash(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    creation_date = db.Column(db.DateTime)
    url_hash = db.Column(db.String(8), unique=True)
    full_url = db.Column(db.String(1000))
    redirects = db.Column(db.Integer)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    user = db.relationship('User',
                           backref=db.backref('hashes', lazy='dynamic'))

    def __init__(self, url_hash, full_url, redirects=0, creation_date=None):
        if creation_date == None:
            self.creation_date = datetime.utcnow()
        self.url_hash = url_hash
        self.full_url = full_url
        self.redirects = redirects
示例#9
0
class Url(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(length=300))
    short_url = db.Column(db.String(length=300))