class StudentModel(UserModel): student_courses_table = db.Table('student_courses', db.Model.metadata, db.Column('student_id', db.Integer, db.ForeignKey('student.id')), db.Column('course_id', db.Integer, db.ForeignKey('course.id')) ) student_majors_table = db.Table('student_majors', db.Model.metadata, db.Column('student_id', db.Integer, db.ForeignKey('student.id')), db.Column('major_id', db.Integer, db.ForeignKey('major.id')) ) __tablename__ = 'student' id = db.Column(db.Integer, db.ForeignKey('booklick_user.id'), primary_key=True) first_name = db.Column(db.String(100)) last_name = db.Column(db.String(100)) description = db.Column(db.String(500)) picture = db.Column(db.String(100)) semester = db.Column(db.Integer) courses = db.relationship("CourseModel", secondary=student_courses_table, backref=db.backref('students', lazy=True)) majors = db.relationship("MajorModel", secondary=student_majors_table, backref=db.backref('students', lazy=True)) __mapper_args__ = { 'polymorphic_identity': 'student', } def __init__(self, username: str, email: str, code: int, first_name: str, last_name: str, password: str, description: str, picture: str, semester: int):
def create_table(self) -> NoReturn: """ creates layout db table if a layouts table does not exist in the database :column id: the layout entry's identification number (auto generated) :type id: int (Primary Key) :column widget_id: the id of the widget the layout belongs to :type widget_id: int (Foreign Key) :column x: x coordinate of the layout :type x: int :column y: y coordinate of the layout :type y: int :column h: height of the layout :type h: int :column w: width of the layout :type w: int :column static: static property of the widget :type static: bool """ if not self.table_exists(): # If table don't exist, Create. # Create a table with the appropriate Columns db.Table('layouts', db.MetaData(bind=db.engine), db.Column('id', db.Integer, primary_key=True), db.Column('widget_id', db.Integer, nullable=True), db.Column('x', db.Integer, nullable=False), db.Column('y', db.Integer, nullable=False), db.Column('h', db.Integer, nullable=False), db.Column('w', db.Integer, nullable=False), db.Column('static', db.Boolean, nullable=False), schema=None).create()
class Invite(db.Model): __tablename__ = 'invite' __table__ = db.Table('invite', Base.metadata, autoload=True, autoload_with=db.engine) def __init__(self,_id,email,token,confirmed): self.id=_id self.email=email self.token=token self.confirmed=confirmed def save_to_db(self): db.session.add(self) db.session.commit() def encrypt_token(email): return pwd_context.encrypt(email) def check_encrypted_token(email, hashed): return pwd_context.verify(email, hashed) @classmethod def find_by_name(cls, email): val= cls.query.filter_by(email=email).first() print(val) return val
class Auth(db.Model): __tablename__ = 'auth' __table__ = db.Table('auth', Base.metadata, autoload=True, autoload_with=db.engine) def __init__(self, id, User_Name, password): self.id = id self.User_Name = User_Name self.password = password def save_to_db(self): db.session.add(self) db.session.commit() @classmethod def find_by_name(cls, User_Name): print(User_Name) val = cls.query.filter_by(User_Name=User_Name).first() print(val) return val @classmethod def find_by_id(cls, User_id): print(User_id) val = cls.query.filter_by(id=User_id).first() print(val) return val
class User(db.Model): __tablename__ = 'user' __table__ = db.Table('user', Base.metadata, autoload=True, autoload_with=db.engine) def __init__(self, User_Name, First_Name, Last_Name, User_Email, phone_no, password): self.User_Name = User_Name self.First_Name = First_Name self.Last_Name = Last_Name self.User_Email = User_Email self.phone_no = phone_no self.password = password def save_to_db(self): db.session.add(self) db.session.commit() def json(self): return { 'User_id': self.User_id, 'User_Name': self.User_Name, 'First_Name': self.First_Name, 'Last_Name': self.Last_Name, 'User_Email': self.User_Email, 'phone_no': self.phone_no, 'Role': self.Role_id } def encrypt_password(password): return pwd_context.encrypt(password) def check_encrypted_password(password, hashed): return pwd_context.verify(password, hashed) @classmethod def find_by_name(cls, User_Name): print(User_Name) val = cls.query.filter_by(User_Name=User_Name).first() print(val) return val @classmethod def find_by_email(cls, User_Email): print(User_Name) val = cls.query.filter_by(User_Email=User_Email).first() print(val) return val @classmethod def find_by_id(cls, User_id): print(User_id) val = cls.query.filter_by(id=User_id).first() print(val) return val
class Team_User(db.Model): __tablename__ = 'user_team_mapping' __table__ = db.Table('user_team_mapping', Base.metadata, autoload=True, autoload_with=db.engine) def __init__(self, Team_id, User_id): self.User_id = User_id self.Team_id = Team_id
class Team(db.Model): __tablename__ = 'teams' __table__ = db.Table('teams', Base.metadata, autoload=True, autoload_with=db.engine) def __init__(self, Team_id, Team_Name): self.Team_Name = Team_Name self.Team_id = Team_id
class Task(db.Model): __tablename__ = 'tasks' __table__ = db.Table('tasks', Base.metadata, autoload=True, autoload_with=db.engine) def __init__(self,Task_id,Title,Description,Priority,Planned_Date,Assignee,Reporter,Status,Team_Name): self.Task_id=Task_id self.Title=Title self.Description=Description self.Priority=Priority self.Planned_Date=Planned_Date self.Assignee=Assignee self.Reporter=Reporter self.Status=Status self.Team_Name=Team_Name def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() def json(self): return {'Task_id':self.Task_id, 'Title': self.Title,'Description': self.Description,'Priority': self.Priority,'Assignee':self.Assignee,'Reporter':self.Reporter,'Status':self.Status,'Team_Name':self.Team_Name} @classmethod def find_by_name(cls, Title): print(Title) val= cls.query.filter_by(Title=Title).first() print(val) return val @classmethod def find_by_id(cls, Task_id): val= cls.query.filter_by(Task_id=Task_id).first() print(val) return val @classmethod def find_by_team(cls, Team_Name): print(Team_Name) val= cls.query.filter_by(Team_Name=Team_Name).first() print(val) return val
def create_table(self) -> NoReturn: """ Create the widget table if it does not exist """ # If table don't exist, Create. if not self.table_exists(): # Create a table with the appropriate Columns db.Table(self._WIDGET_DB_TABLE_NAME, db.MetaData(bind=db.engine), db.Column('id', db.Integer, primary_key=True), db.Column('user_id', db.Integer, nullable=False), db.Column('data', JSON, nullable=False), db.Column('layout_id', db.Integer, db.ForeignKey('layouts.id')), db.relationship('Layouts', backref=db.backref('layouts', lazy=True)), schema=None).create()
def get(self): insp = reflection.Inspector.from_engine(db.engine) print(insp.get_view_names()) user_email = get_jwt_identity() user = UserModel.find_by_email(user_email) res_stat = [] perform_stat = [] results_set = [] date_stat = {} MyView = db.Table("stat_by_date", metadata, db.Column("score_id", db.Integer, primary_key=True), extend_existing=True, autoload=True) try: query = MyView.select().order_by(MyView.c.date).where(MyView.c.user_id == user.id) results = db.engine.execute(query) if not results: return { 'message': 'The record is empty' }, 204 for row in results: results_set.append(dict(row)) for idx, result in enumerate(results_set): stat = {} date = result['date'].strftime('%b %d, %Y') if idx > 0 and result['date'] != results_set[idx-1]['date']: date = result['date'].strftime('%b %d, %Y') res_stat=[] for key, val in result.items(): if key != 'date' and key != 'user_id': stat[key] = val res_stat.append(stat) if idx == len(results_set)-1 or result['date'] != results_set[idx+1]['date']: date_stat = {'date': date, 'stats': res_stat} perform_stat.append(date_stat) response = jsonify(perform_stat) response.status_code = 200 return response except Exception as e : print(e) return { 'message': 'Something went wrong!' }, 501
class BooklistModel(db.Model): association_table = db.Table( 'booklist_contents', db.Model.metadata, db.Column('booklists_id', db.Integer, db.ForeignKey('booklists.id')), db.Column('contents_id', db.Integer, db.ForeignKey('contents.id')), ) __tablename__ = 'booklists' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) description = db.Column(db.String(80)) imageURL = db.Column(db.String(80)) contents = db.relationship("ContentModel", secondary=association_table) user_id = db.Column(db.Integer, db.ForeignKey('booklick_user.id')) def __init__(self, name, description, imageURL): self.name = name self.description = description self.imageURL = imageURL def json(self): return { 'name': self.name, 'description': self.description, 'imageURL': self.imageURL, 'contents': [content.json() for content in self.contents], } @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class ProfessorModel(UserModel): professor_courses_table = db.Table( 'professor_courses', db.Model.metadata, db.Column('professor_id', db.Integer, db.ForeignKey('professor.id')), db.Column('course_id', db.Integer, db.ForeignKey('course.id'))) __tablename__ = 'professor' id = db.Column(db.Integer, db.ForeignKey('booklick_user.id'), primary_key=True) first_name = db.Column(db.String(100)) last_name = db.Column(db.String(100)) description = db.Column(db.String(500)) picture = db.Column(db.String(100)) courses = db.relationship("CourseModel", secondary=professor_courses_table, backref=db.backref('professors', lazy=True)) __mapper_args__ = { 'polymorphic_identity': 'professor', } def _init_(self, username: str, email: str, code: int, first_name: str, last_name: str, password: str, description: str, picture: str): self.username = username self.email = email self.code = code self.first_name = first_name self.last_name = last_name self.password = password self.description = description self.picture = picture def json(self): return { 'first_name': self.first_name, 'last_name': self.last_name, 'username': self.username, 'email': self.email, 'code': self.code, 'description': self.description, 'picture': self.picture }
from db import db b = db.Table( 'b', db.Column('wishlist_id', db.Integer, db.ForeignKey('wishlists.id')), db.Column('book_id', db.Integer, db.ForeignKey('books.id'))) class WishlistModel(db.Model): __tablename__ = 'wishlists' id = db.Column(db.Integer, primary_key=True) id_account = db.Column(db.Integer, db.ForeignKey('accounts.id'), nullable=False) # books = db.relationship('BookModel', backref='books_wl', lazy=True) books = db.relationship('BookModel', secondary=b, backref=db.backref('book_wl', lazy='dynamic')) def __init__(self, id_account): self.id_account = id_account @classmethod def find_by_id(cls, idd): return db.session.query(WishlistModel).filter_by(id=idd).first() @classmethod def find_by_account(cls, id_account): return db.session.query(WishlistModel).filter_by( id_account=id_account).first()
import sqlite3 from sqlalchemy import Boolean, Column, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy import DateTime, Integer, String, Text, Float, Boolean from db import db from models.mysql.permiso import Permiso permisoXUsuario = db.Table('permisosxUsuarios', db.Column('usuario_id', db.Integer, db.ForeignKey('usuarios.id')), db.Column('permiso_id', db.Integer, db.ForeignKey('permisos.id_permiso')) ) class Usuario(db.Model): __tablename__ = 'usuarios' __table_args__ = {'mysql_engine':'InnoDB','mysql_charset':'utf8','mysql_collate':'utf8_general_ci'} id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(60)) nombre = db.Column(String(30)) password = db.Column(String(80)) habilitado = db.Column(db.Boolean, default = True, nullable=True) direccion = db.Column(String(50)) telefono = db.Column(String(120)) permisos = db.relationship('Permiso',secondary =permisoXUsuario, backref = db.backref('permisos'),lazy = 'dynamic') id_grupoDeTrabajo = db.Column(db.Integer,default = 0) esJefeDe = db.Column(db.Integer,default = 0) def __init__(self, nombre, email, password,direccion,telefono,permisos,id_grupoDeTrabajo,esJefeDe): from servicios.permisosService import PermisosService self.nombre = nombre self.email = email self.password = password
from config import Configuration from db import db from models.tag import TagModel from models.category import CategoryModel post_tags = db.Table( 'post_tags', db.Column('post_id', db.Integer, db.ForeignKey('posts.id')), db.Column('tag_id', db.Integer, db.ForeignKey(TagModel.id))) class PostModel(db.Model): __tablename__ = 'posts' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(Configuration.MAX_POST_TITLE_SIZE)) body = db.Column(db.Text) user_id = db.Column(db.Integer, nullable=False) is_published = db.Column(db.Boolean, nullable=False) tags = db.relationship('TagModel', secondary=post_tags, backref=db.backref('posts'), lazy='dynamic') category_id = db.Column('category_id', db.Integer, db.ForeignKey(CategoryModel.id)) comments = db.relationship('models.comment.CommentModel', backref=db.backref('posts'),
from db import db from models.genre import GenreModel from models.actor import ActorModel from models.language import LanguageModel from models.country import CountryModel from models.rating import RatingModel genres = db.Table( 'movies_genres', db.Column('moviesId', db.Integer, db.ForeignKey('movies.id'), primary_key=True), db.Column('genresId', db.Integer, db.ForeignKey('genres.id'), primary_key=True)) actors = db.Table( 'movies_actors', db.Column('moviesId', db.Integer, db.ForeignKey('movies.id'), primary_key=True), db.Column('actorsId', db.Integer, db.ForeignKey('actors.id'), primary_key=True)) languages = db.Table(
from db import db post_tags = db.Table('post_tags', db.Column('tag_id', db.Integer, db.ForeignKey('tags.id'), primary_key=True), db.Column('post_id', db.Integer, db.ForeignKey('posts.id'), primary_key=True) ) class TagModel(db.Model): __tablename__ = 'tags' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), nullable=False, unique=True) posts = db.relationship('PostModel',secondary=post_tags, back_populates="tags") def json(self): return { "id":self.id, "name":self.name }
from db import db from ma import ma recipe_measure = db.Table('recipe_measure', db.Column('recipe_id', db.Integer, db.ForeignKey('recipe.id'), primary_key=True), db.Column('measure_id', db.Integer, db.ForeignKey('measure.id'), primary_key=True) ) class Unit(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False, unique=True) class Recipe(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), nullable=False, unique=True) class Measure(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) quantity = db.Column(db.Integer, nullable=False) ingredient_id = db.Column(db.Integer, db.ForeignKey('ingredient.id'), nullable=False) unit_id = db.Column(db.Integer, db.ForeignKey('unit.id'), nullable=False) recipe = db.relationship('Recipe', secondary=recipe_measure, lazy='joined', backref=db.backref('measures', lazy=True)) ingredient = db.relationship('Ingredient', lazy='joined', backref=db.backref('ingredient', lazy=True)) unit = db.relationship('Unit', backref=db.backref('unit', uselist=False)) class Ingredient(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), nullable=False, unique=True) class UnitSchema(ma.SQLAlchemyAutoSchema):
from db import db inventory_table = db.Table( 'inventory', db.Column('id', db.Integer, primary_key=True), db.Column('store_id', db.Integer, db.ForeignKey('store.id')), db.Column('item_id', db.Integer, db.ForeignKey('item.id')), db.Column('quantity', db.Integer), db.Column('mark_down', db.Integer, default=0), ) class StoreModel(db.Model): """ Store should be a many to many with ItemModel. Base class is provided by the frame work. Same concept as sqlalchemy - db.Model DB notes: flavor? but plural for stores table name, is ? others say 'store' code thought: What if i created a core class say: class CoreClassAPI(object): def json(self): def find(cls,string): def save(self): def insert(self): def delete(self): def update(self): The class could be inherited by the model, providing less code """
from db import db st_rooms = db.Table( 'st_rooms', db.Column('st_id', db.String, db.ForeignKey('staff.pass_id')), db.Column('room_num', db.Integer, db.ForeignKey('room.number')) ) class Staff(db.Model): pass_id = db.Column(db.String, primary_key=True) name = db.Column(db.String, nullable=False) position = db.Column(db.String, nullable=False) salary = db.Column(db.Float) rooms = db.relationship('Room', secondary=st_rooms, backref='staff')
tenants = db.relationship('TenantModel', backref='room') class TenantModel(db.Model): __tablename__ = 'tenant_table' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(50), nullable=False) passport_id = db.Column(db.String(10), unique=True, nullable=False) age = db.Column(db.Integer, nullable=False) sex = db.Column(db.String(10), nullable=False) address = db.Column(db.JSON, nullable=False) room_number = db.Column(db.Integer, db.ForeignKey('room_table.number')) stuff_to_room = db.Table( 'stuff_to_room', db.Column('room_number', db.Integer, db.ForeignKey('room_table.number')), db.Column('stuff_id', db.Integer, db.ForeignKey('stuff_table.id'))) class StuffModel(db.Model): __tablename__ = 'stuff_table' id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(50), unique=True, nullable=False) passport_id = db.Column(db.String(10), unique=True, nullable=False) position = db.Column(db.String(50), nullable=False) salary = db.Column(db.Integer, nullable=False) serving = db.relationship('RoomModel', secondary=stuff_to_room, backref=db.backref('rooms'))
from db import db staff_rooms = db.Table( "staff_rooms", db.Column('passport_ID', db.Integer, db.ForeignKey('staff.passport_ID')), db.Column('number', db.Integer, db.ForeignKey('rooms.number'))) class StaffModel(db.Model): __tablename__ = "staff" passport_ID = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, unique=True, nullable=True) position = db.Column(db.String, unique=True, nullable=True) salary = db.Column(db.Integer, unique=False, nullable=True) rooms = db.relationship('RoomsModel', secondary=staff_rooms, backref=db.backref('rooms')) class RoomsModel(db.Model): __tablename__ = "rooms" number = db.Column(db.Integer, primary_key=True) level = db.Column(db.String) status = db.Column(db.String, unique=False) price = db.Column(db.Integer) tenant_ID = db.Column(db.Integer, db.ForeignKey('tenants.passport_ID')) class TenantsModel(db.Model):
from db import db from models.servicenote import ServiceNote language_association = db.Table( 'language_association', db.Column('person_id', db.Integer, db.ForeignKey('person.id'), primary_key=True), db.Column('language_id', db.Integer, db.ForeignKey('language.id'), primary_key=True), ) class Person(db.Model): id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String) last_name = db.Column(db.String) email = db.Column(db.String) phone = db.Column(db.String) origin_country = db.Column(db.String) languages = db.relationship('Language', secondary=language_association) def service_notes(self, service: int): return ServiceNote.query.filter_by(service_id=service).all()
from flask_authorize import RestrictionsMixin, AllowancesMixin from flask_login import UserMixin from db import db from typing import List # mapping tables UserGroup = db.Table( 'user_group', db.Model.metadata, db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('group_id', db.Integer, db.ForeignKey('groups.id'))) UserRole = db.Table( 'user_role', db.Model.metadata, db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('role_id', db.Integer, db.ForeignKey('roles.id'))) class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100)) password = db.Column(db.String(100)) name = db.Column(db.String(1000)) # `roles` and `groups` are reserved words that *must* be defined # on the `User` model to use group- or role-based authorization. roles = db.relationship('Role', secondary=UserRole) groups = db.relationship('Group', secondary=UserGroup) @classmethod
from db import db author_works = db.Table( 'author_works', db.Column('author_id', db.Integer, db.ForeignKey('author.author_id')), db.Column('book_id', db.Integer, db.ForeignKey('book.book_id'))) class Author(db.Model): author_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) works = db.relationship('Book', secondary=author_works, backref=db.backref('works')) class Book(db.Model): book_id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String)
from models.classes import ClassesModel, ClassesJSON from models.skills import SkillsModel, SkillsJSON from models.collaborations import CollabJSON # Costume(custom JSON) return type, will help in type hinting UserJSON = Dict[str, Union[str, str, str, str, List[SkillsJSON], List[ClassesJSON], List[CollabJSON]]] """ Association tables that will be the connector in a Many-to-Many relationship between two tables. skills: Will associate skills required for a collab to the collabs that have specified them. classes: Will associate classes required for a collab to the collabs that have specified them. members: Will associate members required for a collab to the collabs that the user has joined """ skills_association = db.Table( "user_skills", db.Column("user_id", db.Integer, db.ForeignKey("users.id")), db.Column("skill_id", db.Integer, db.ForeignKey("skills.id")), ) classes_association = db.Table( "user_classes", db.Column("user_id", db.Integer, db.ForeignKey("users.id")), db.Column("class_id", db.Integer, db.ForeignKey("classes.id")), ) collabs_association = db.Table( "user_collabs", db.Column("user_id", db.Integer, db.ForeignKey("users.id")), db.Column("collab_id", db.Integer, db.ForeignKey("collaborations.id")), )
# attempts_number = db.Column(db.Integer,) # # def __init__(self, game_id, player_id, attempts_number): # self.game_id = game_id # self.player_id = player_id # self.attempts_number = attempts_number # # # import random from db import db game_players = db.Table( 'game_players', db.Column('user_id', db.Integer, db.ForeignKey('game_user.id')), db.Column('game_id', db.Integer, db.ForeignKey('game.id'))) class Game(db.Model): id = db.Column(db.Integer, primary_key=True) secret_number = db.Column(db.Integer, default=random.randint(0, 10)) attempt = db.Column(db.Integer) status = db.Column(db.String, default='active') author_id = db.Column(db.Integer, db.ForeignKey('game_user.id')) players = db.relationship('GameUsers', secondary=game_players, backref=db.backref('players')) range_from = db.Column(db.Integer) range_to = db.Column(db.Integer) winner_id = db.Column(db.Integer, db.ForeignKey('game_user.id'))
from db import db user_bike = db.Table( 'user_bike', db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('ebike_id', db.Integer, db.ForeignKey('ebikes.id'))) class UserModel(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(80)) last_name = db.Column(db.String(80)) password = db.Column(db.String(80)) email = db.Column(db.String(80)) ebikes = db.relationship('EbikeModel', secondary=user_bike, back_populates='users') def __init__(self, email, first_name, last_name, password): self.email = email self.first_name = first_name self.last_name = last_name self.password = password def json(self): return { 'id': self.id, 'first_name': self.first_name, 'last_name': self.last_name,
from db import db book_tag_table = db.Table( 'book_tag', db.Model.metadata, db.Column('book_id', db.Integer, db.ForeignKey('book.id')), db.Column('tag_id', db.Integer, db.ForeignKey('tag.id')))
import enum from db import db class UsageTypeEnum(enum.Enum): KILOWATT = 'KILOWATT' WATER_PER_HOUR = 'WATER_PER_HOUR' WATER_PER_USAGE = 'WATER_PER_USAGE' value = None @classmethod def has_value(cls, value): return any(value == item.value for item in cls) def is_kilowatt(self): return self.value == self.KILOWATT.value def is_water_per_hour(self): return self.value == self.WATER_PER_HOUR.value def is_water_per_usage(self): return self.value == self.WATER_PER_USAGE.value t = db.Table('usage_type_enum', db.MetaData(), db.Column('value', db.Enum(UsageTypeEnum)))