Created
June 7, 2015 02:33
-
-
Save miohtama/ac44f58f67d8b5a12040 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import string | |
from urllib.parse import urlparse | |
import random | |
from sqlalchemy import ( | |
Column, | |
Index, | |
Integer, | |
String, DateTime, ForeignKey) | |
from pyramid_web20.models import Base, utc, now, DBSession | |
from sqlalchemy.ext.declarative import declared_attr | |
from sqlalchemy.orm import relationship | |
def assert_valid_short_url(url): | |
# XXX: Probably very buggy, but works for now | |
pieces = urlparse(url) | |
assert all([pieces.scheme, pieces.netloc]) | |
assert set(pieces.netloc) <= set(string.ascii_letters + string.digits + '-.') # and others? | |
assert pieces.scheme in ['http', 'https'] | |
class ReferralBase(Base): | |
"""A shorted URL in the database. | |
This class is abstract and doesn't know about "owner" as the user model can change depending on the host application. Instead, the concrete implementation is provided in ``defaultmodels.py`` | |
""" | |
__tablename__ = 'referrals' | |
__abstract__ = True | |
id = Column(Integer, primary_key=True) | |
created_at = Column(DateTime(timezone=utc), default=now) | |
updated_at = Column(DateTime(timezone=utc), onupdate=now) | |
slug = Column(String(6), unique=True) | |
hits = Column(Integer, default=0) | |
@declared_attr | |
def owner_id(self, cls): | |
raise NotImplementedError() | |
@declared_attr | |
def owner(self, cls): | |
raise NotImplementedError() | |
def create_referral_class(UserModel) -> type: | |
"""Creates a concrete implementation of Referral class with specifc user model as owner relationship. | |
:param UserModel: | |
:return: ReferralBase-like class | |
""" | |
class Referral(ReferralBase): | |
@declared_attr | |
def owner_id(cls): | |
return Column(Integer, ForeignKey('{}.id'.format(UserModel.__tablename__))) | |
@declared_attr | |
def owner_id(cls): | |
return relationship(UserModel, backref="referrals") | |
return Referral | |
# in the app | |
from foo import UserModel | |
_referral = create_referral_class(UserModel) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment