class RelUserProject(JsonSerializer, db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) project_id = db.Column(db.Integer, db.ForeignKey("projects.id")) created_at = db.Column(db.DateTime, default=db.func.now()) updated_at = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) user = db.relationship("Users", backref=db.backref("projects", lazy="dynamic")) project = db.relationship("Projects", backref=db.backref("users", lazy="dynamic"))
class Alias(db.Model): id = db.Column(db.Integer, primary_key=True) owner_id = db.Column(db.Integer, db.ForeignKey('user.id')) domain_id = db.Column(db.Integer, db.ForeignKey('domain.id')) alias = db.Column(db.String(255), index=True, nullable=False) forward = db.Column(db.String(255), nullable=False) comment = db.Column(db.Text, default='') enabled = db.Column(db.Boolean, default=True) expires = db.Column(db.DateTime, default=None) num_accepted = db.Column(db.Integer, default=0) num_rejected = db.Column(db.Integer, default=0) domain = db.relationship('Domain', backref=db.backref('aliases', lazy=True)) owner = db.relationship('User', backref=db.backref('aliases'))
class Sessions(JsonSerializer, db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) session = db.Column(db.String(32)) expired = db.Column(db.Integer) created_at = db.Column(db.DateTime, default=db.func.now()) updated_at= db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) user = db.relationship("Users", backref=db.backref("sessions", lazy="dynamic"))
class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) # User authentication information username = db.Column(db.String(50), nullable=False, unique=True) password = db.Column(db.String(255), nullable=False, server_default='') reset_password_token = db.Column(db.String(100), nullable=False, server_default='') # User email information email = db.Column(db.String(255), nullable=False, unique=True) confirmed_at = db.Column(db.DateTime()) # User information active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0') finished_role_selection = db.Column('finished_role_selection', db.Boolean(), default=False) first_name = db.Column(db.String(100), nullable=False, server_default='') last_name = db.Column(db.String(100), nullable=False, server_default='') # user_types are: teacher, student, general # user_type = db.Column(db.String(100), nullable=False,server_default='general') roles = db.relationship('Role', secondary='user_roles', backref=db.backref('users', lazy='dynamic')) episodes = db.relationship('Episode', secondary=episodes, backref=db.backref('users', lazy='dynamic')) teachers = db.relationship('User', secondary=teachers, primaryjoin=(teachers.c.student_id == id), secondaryjoin=(teachers.c.teacher_id == id), backref=db.backref('students', lazy="dynamic"), lazy="dynamic") def addTeacher(self, teacher): if not self.has_teacher(teacher): self.teachers.append(teacher) return self def removeTeacher(self, teacher): if self.has_teacher(teacher): self.teachers.remove(teacher) return self def has_teacher(self, teacher): return self.teachers.filter(teachers.c.teacher_id == teacher.id).count() > 0
class Marks(db.Model): __tablename__ = 'marks' id = db.Column(db.Integer, primary_key=True, autoincrement=True) bsr = db.Column(db.Integer, nullable=False) price = db.Column(db.Integer, nullable=False) stock = db.Column(db.String(10), nullable=False) uptime = db.Column(db.DateTime, default=datetime.datetime.now) asin_id = db.Column(db.Integer, db.ForeignKey("listing.id")) listing = db.relationship("Listing", backref=db.backref('marks'))
class Deploys(JsonSerializer, db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) project_id = db.Column(db.Integer, db.ForeignKey("projects.id")) host_id = db.Column(db.Integer, db.ForeignKey("hosts.id")) mode = db.Column(db.Integer) branch = db.Column(db.String(32)) version = db.Column(db.String(32)) progress = db.Column(db.Integer, default=0) status = db.Column(db.Integer, default=0) softln_filename = db.Column(db.String(64)) comment = db.Column(db.Text, default="") created_at = db.Column(db.DateTime, default=db.func.now()) updated_at = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) user = db.relationship("Users", backref=db.backref("deploys", lazy="dynamic")) project = db.relationship("Projects", backref=db.backref("deploys", lazy="dynamic")) host = db.relationship("Hosts", backref=db.backref("deploys", lazy="dynamic"))
class Hosts(JsonSerializer, db.Model): __json_hidden__ = ["deploys", "users"] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) ssh_host = db.Column(db.String(32)) ssh_port = db.Column(db.Integer) ssh_user = db.Column(db.String(64)) ssh_pass = db.Column(db.String(100)) created_at = db.Column(db.DateTime, default=db.func.now()) updated_at= db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) users = db.relationship("Users", secondary=rel_user_host, backref=db.backref("hosts", lazy="dynamic"))
class User(db.Model, UserMixin): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=False) email = db.Column(db.String(120), unique=True, nullable=False) phone_no = db.Column(db.String(15), unique=True, nullable=False) password = db.Column(db.String(60), nullable=False) is_working = db.Column(db.Boolean, nullable=False, default=True) active = db.Column('is_active', db.Boolean(), nullable=False, server_default='0') roles = db.relationship('Role', secondary='user_roles', backref=db.backref('users', lazy='dynamic')) def has_roles(self, *args): return set(args).issubset({role.name for role in self.roles}) def __repr__(self): return f"User('{self.id}', '{self.phone_no}', '{self.username}', '{self.email}', '{self.is_working}')"
class Event(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) title = db.Column(db.String(128)) content = db.Column(db.String(256)) date = db.Column(db.String(256)) members = db.Column(db.Integer, default=0) author_login = db.Column(db.String(128), db.ForeignKey('user.login')) author = db.relationship('User', backref=db.backref('events')) def __init__(self, title, content, date, author_login): self.title = title self.content = content self.date = date self.author_login = author_login def save(self): db.session.add(self) db.session.commit() return self.id # Получает список всех мероприятий @staticmethod def get_all(): events = list(reversed(Event.query.all())) return events # Получает список мероприятий, созданных конкретным пользователем @staticmethod def get_user_events(login): events = Event.query.all() user_events = [] for event in events: if event.author_login == login: user_events.append(event) user_events.reverse() return user_events # Получает мероприятие по его id @staticmethod def get_event(id): events = Event.query.all() for event in events: if event.id == id: return event
class Order(db.Model, UserMixin): __tablename__ = 'orders' # Order Details id = db.Column(db.Integer, primary_key=True) # metadata date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) status = db.Column(db.Enum(OrderStatus), nullable=False, default=OrderStatus.accepted) # User/Agent details user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User', backref=db.backref('user', lazy='dynamic')) user_tip = db.Column(db.Float, default=0.0) # Customer details cust_name = db.Column(db.String(30), nullable=False) phone = db.Column(db.String(15), nullable=False) cust_addr1 = db.Column(db.String(65), nullable=False) cust_addr2 = db.Column(db.String(65), nullable=True) cust_pincode = db.Column(db.String(12), nullable=False) #Delivery Details delivery_instructions = db.Column(db.String(300), nullable=True)
class Projects(JsonSerializer, db.Model): __json_hidden__ = ["deploys", "users"] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True) repo_url = db.Column(db.String(200)) checkout_dir = db.Column(db.String(200)) target_dir = db.Column(db.String(200)) deploy_dir = db.Column(db.String(200)) deploy_history_dir = db.Column(db.String(200)) before_checkout = db.Column(db.Text, default="") after_checkout = db.Column(db.Text, default="") before_deploy = db.Column(db.Text, default="") after_deploy = db.Column(db.Text, default="") created_at = db.Column(db.DateTime, default=db.func.now()) updated_at = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) users = db.relationship("Users", secondary=rel_user_project, backref=db.backref("projects", lazy="dynamic"))
class Movie(db.Model): __searchable__ = ['description', ] id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(140), nullable=False) original_title = db.Column(db.String(140), nullable=True) slug = db.Column(db.String(64), nullable=False, unique=True) wiki_url = db.Column(db.String(64), nullable=True) image = db.Column(db.String(64), nullable=True) description = db.Column(db.UnicodeText) timestamp = db.Column(db.DateTime) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) genres = db.relationship( 'Genre', secondary=movie_genres, # primaryjoin=(movie_genres.c.movie_id == id), # secondaryjoin=(movie_genres.c.genre_id == id), backref=db.backref('movies', lazy='dynamic'), lazy='dynamic', ) directors = db.relationship( 'Person', secondary=movie_directors, # primaryjoin=(movie_genres.c.movie_id == id), # secondaryjoin=(movie_genres.c.genre_id == id), backref=db.backref('directed', lazy='dynamic'), lazy='dynamic', ) def __repr__(self): return "<Movie {}>".format(self.title) @staticmethod def make_slug(title): ''' Making slug ''' slug = slugify(title) if Movie.query.filter_by(slug=slug).first() is None: return slug version = 2 while True: new_slug = slug + str(version) if Movie.query.filter_by(slug=new_slug).first() is None: break version += 1 return new_slug def normalize(self, user_id): if not self.user_id: self.user_id = user_id self.timestamp = datetime.utcnow() def has_genre(self, genre): if genre is None: return False return self.genres.filter(movie_genres.c.genre_id == genre.id).count() > 0 def add_genre(self, genre): if genre is None: return self if not self.has_genre(genre): self.genres.append(genre) return self def del_genre(self, genre): if genre is None: return self if self.has_genre(genre): self.genres.remove(genre) return self def has_director(self, director): if director is None: return False return self.directors.filter(movie_directors.c.person_id == director.id).count() > 0 def add_director(self, director): print('ADD DIRECTOR', director) if director is None: return self if not self.has_director(director): self.directors.append(director) return self def del_director(self, director): if director is None: return self if self.has_director(director): self.directors.remove(director) return self def update_genres(self, genres): for genre in self.genres: if genre not in genres: self.del_genre(genre) for genre in genres: if genre: self.add_genre(genre) return self def update_directors(self, directors): print("DIRECTORS", directors) for director in self.directors: if director not in directors: self.del_director(director) for director in directors: if director: self.add_director(director) print("DIRECTORS", self.directors.all()) return self @property def genre_names(self): return ', '.join([genre.title.lower() for genre in self.genres]).capitalize() def avatar(self, width=128, height=None): if self.image: try: url = url_for('static', filename="upload/{}".format(self.image)) constraints = [] if width: constraints.append(str(width)) else: constraints.append('') if height: constraints.append(str(height)) size = "x".join(constraints) return resize(url, str(size)) except: pass if (height is None) or (width < height): size = width else: size = height return gravatar(self.slug, size) def as_dict(self): d = {c.name: getattr(self, c.name) for c in self.__table__.columns} d['genres'] = [g.title for g in self.genres] d['directors'] = [p.slug for p in self.directors] return d def from_dict(self, data): for k, v in data.items(): if k in self.__table__.columns: setattr(self, k, v) db.session.add(self) genres = data.get('genres', []) for g in genres: genre = Genre.query.filter_by(title=g).first() if genre is None: genre = Genre(title=g) db.session.add(genre) self.add_genre(genre) directors = data.get('directors', []) for p in directors: director = Person.query.filter_by(slug=p).first() if director is None: director = Person(slug=p) db.session.add(director) self.add_director(director) @staticmethod def from_yml(data, user_id=None): movies = [] for d in data: m = Movie() # {'slug': 'sekretnye-materialy'} slug = d.get('slug') slug = Movie.make_slug(slug) m.from_dict({ "title": d.get('title', 'UNTITLED'), "slug": slug, "wiki_url": d.get('wiki_url'), "image": d.get('image'), "description": d.get('description'), "user_id": user_id, "timestamp": d.get('timestamp', datetime.utcnow()), "genres": d.get('genres', []), "directors": d.get('directors', []), }) movies.append(m) return movies @property def wikipage(self): if self.wiki_url: return self.wiki_url return self.title @property def wikipedia(self): return "https://ru.wikipedia.org/wiki/{}".format(self.wikipage) # Query shortcuts @staticmethod def ordered(order_by=''): q = Movie.query if order_by == 'alpha': q = q.order_by(Movie.title) else: q = q.order_by(Movie.timestamp.desc()) return q @staticmethod def by_slug(slug): return Movie.query.filter_by(slug=slug).first_or_404() @staticmethod def by_genre(genre, order_by=''): q = Movie.ordered(order_by) if genre is None: return q.filter(~Movie.genres.any()) return q.filter(Movie.genres.contains(genre)) @staticmethod def by_director(director, order_by=''): q = Movie.ordered(order_by) if director is None: return q.filter(~Movie.directors.any()) return q.filter(Movie.directors.contains(director)) @staticmethod def by_random(): return Movie.query.order_by(func.random())
class User(db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column(db.String(64), index=True, unique=True) email = db.Column(db.String(120), index=True, unique=True) role = db.Column(db.SmallInteger, default=ROLE_USER) posts = db.relationship('Post', backref='author', lazy='dynamic') movies = db.relationship('Movie', backref='posted_by', lazy='dynamic') about_me = db.Column(db.String(140)) last_seen = db.Column(db.DateTime) followed = db.relationship( 'User', secondary=followers, primaryjoin=(followers.c.follower_id == id), secondaryjoin=(followers.c.followed_id == id), backref=db.backref('followers', lazy='dynamic'), lazy='dynamic', ) def __repr__(self): # pragma: no cover return "<User {}>".format(self.nickname) @property def is_authenticated(self): return True @property def is_active(self): return True @property def is_anonimous(self): return False def get_id(self): try: return unicode(self.id) except NameError: return str(self.id) def avatar(self, size): return gravatar(self.email, size) @staticmethod def make_valid_nickname(nickname): import re return re.sub('[^\w]', '', nickname) @staticmethod def make_unique_nickname(nickname): if User.query.filter_by(nickname=nickname).first() is None: return nickname version = 2 while True: new_nickname = nickname + str(version) if User.query.filter_by(nickname=new_nickname).first() is None: break version += 1 return new_nickname def follow(self, user): if not self.is_following(user): self.followed.append(user) return self def unfollow(self, user): if self.is_following(user): self.followed.remove(user) return self def is_following(self, user): return self.followed.filter( followers.c.followed_id == user.id).count() > 0 def followed_posts(self): return Post.query.join( followers, (followers.c.followed_id == Post.user_id)).filter( followers.c.follower_id == self.id).order_by( Post.timestamp.desc()) # Query shortcuts @staticmethod def by_username(username): return User.query.filter_by(nickname=username).first()