Ejemplo n.º 1
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(64), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    tasks = db.relationship('Todo', backref='tasker', lazy=True)

    def __str__(self):
        return [self.username, self.email]
Ejemplo n.º 2
0
class Patient(db.Model):
    ssn_id = db.Column(db.String(50), unique=True)
    patient_id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    age = db.Column(db.Integer)
    # Change to date type
    admission_date = db.Column(db.Integer)
    bed_type = db.Column(db.String(15))
    address = db.Column(db.String(200))
    city = db.Column(db.String(50))
    state = db.Column(db.String(50))
    status = db.Column(db.String(15))
    med_list = db.relationship('Track_Medicines', backref='patient', lazy=True)
Ejemplo n.º 3
0
class Questions(db.Model):
    __tablename__ = "questions"
    id = db.Column(db.Integer, primary_key=True)
    module_id = db.Column(db.Integer, nullable=False)
    question_type = db.Column(db.Integer, nullable=False)
    creator_id = db.Column(db.Integer, nullable=False)
    is_active = db.Column(db.Boolean, default=True)
    question = db.Column(db.String(2000), nullable=False)
    options = db.relationship('Options', backref='enquiry', lazy=True)
    insert_date = db.Column(db.DateTime,
                            nullable=False,
                            default=datetime.utcnow())
    update_date = db.Column(db.DateTime,
                            nullable=False,
                            default=datetime.utcnow())

    def __repr__(self):
        return '{"id":{0}, "question":{1}}'.format(self.id, self.question)

    @classmethod
    def get_all_questions(classname):
        questions_list = Questions.query.all()
        questions = [question.serialize() for question in questions_list]
        return questions

    @classmethod
    def get_question_from_id(classname, id):
        question = classname.query.get(id)
        return question

    @classmethod
    def delete_question_from_id(classname, id):
        question = classname.get_question_from_id(id)
        if question is None:
            return None
        #first delete the options
        #TODO: currently the deletions of options and question is not atmoic
        options = Options.delete_options_from_qid(id)
        db.session.delete(question)
        db.session.commit()
        return question

    @classmethod
    def submit_question_from_json(classname, json_question):
        question = classname(question=json_question['question'])
        question.module_id = int(json_question['module_id'])
        question.creator_id = int(json_question['creator_id'])
        question.question_type = int(json_question['question_type'])
        db.session.add(question)
        db.session.commit()
        #todo: make options and question creation atomic
        Options.submit_options_from_json(json_question['options'], question.id)
        return question

    #todo:json encoding needed
    def serialize(self):
        json_question = {
            'id': self.id,
            'module_id': self.module_id,
            'question_type': self.question_type,
            'creator_id': self.creator_id,
            'is_active': self.is_active,
            'question': self.question,
            'insert_date': str(self.insert_date),
            'update_date': str(self.update_date),
            'options': Options.serialize_all(self.options)
        }
        return json_question

    @staticmethod
    def validate_question(question):
        if ('question' in question and 'module_id' in question
                and 'question_type' in question):
            return True
        else:
            return False
Ejemplo n.º 4
0
class Users(db.Model):
	__tablename__ =  "users"
	id = db.Column(db.Integer, primary_key=True)
	username = db.Column(db.String(80), nullable=False)
	firstname = db.Column(db.String(80), nullable=True)
	lastname = db.Column(db.String(80), nullable=True)
	email = db.Column(db.String(80), nullable=False)
	password = db.Column(db.String(80), nullable=False)
	registered_on = db.Column(db.DateTime, nullable=False, default=datetime.now())
	isrecruiter = db.Column(db.Boolean, nullable=False, default=False)
	isactive = db.Column(db.Boolean, nullable=False, default=False)
	details = db.relationship('Seekerdetails', backref='enquiry', lazy=True)

	def __repr__(self):
		return '{"username": {0}, "email": {1}, "recruiter": {2} }'.format(self.username, self.email, self.isrecruiter)


	def fullname(self):
		return "{} {}".format(self.firstname, self.lastname)

	@classmethod
	def username_password_match(classname, _email, _password):
		print(_email, _password)
		user = classname.query.filter_by(email=_email).first()
		if user and bcrypt.check_password_hash(user.password, _password):
			print("exists")
			return user
		else:
			print("absent")
			return None

	@classmethod
	def add_user(classname, _user):
		try:
			pw_hash = bcrypt.generate_password_hash(_user.password)
			_user.password = pw_hash
			db.session.add(_user)
			db.session.commit()
		except Exception as e:
			return e

		return classname.get_user_by_username(_user.username)

	@classmethod
	def get_all_users(classname):
		return [user.serialize() for user in classname.query.all()]

	@classmethod
	def get_user_by_username(classname, _username):
		try:
			user_object = classname.query.filter_by(username=_username).first()
			if(user_object == None):
				return user_object
			else:
				return user_object.serialize()
		except:
			return False
	@classmethod
	def get_users_from_text(classname, text):
		query = """select id, Users.firstname, Users.lastname from Users where Users.firstname like "%{}%"
		 or Users.lastname like "%{}%" or Users.username like "%{}%" """.format(text, text, text)
		result = db.engine.execute(query)
		list_result =[]
		for user in result:
			user_dict = {}
			user_dict['id'] = user[0]
			user_dict['label'] = "{} {}".format(user[1], user[2])
			list_result.append(user_dict)
		return list_result


	@classmethod
	def get_user_by_email(classname, _email):
		try:
			user_object = classname.query.filter_by(email=_email).first()
			if(user_object == None):
				return user_object
			else:
				return user_object.serialize()
		except:
			return False

	@classmethod
	def get_user_by(classname, id):
		user_object = classname.query.get(id)
		if(user_object == None):
			return None
		else:
			return user_object

	@classmethod
	def delete_user_by_username(classname, _username):
		try:
			classname.query.filter_by(username=_username).delete()
			db.session.commit()
		except:
			return False

		return True


	@classmethod
	def update_user_by_username(classname, _username, _user):
		try:
			user_to_update = classname.query.filter_by(username=_username).first()
			user_to_update.email = _user.email
			user_to_update.password = _user.password
			db.session.commit()
		except:
			return False

		return classname.get_user_by_username(_user.username)

	@staticmethod
	def validate_user(user):
		if ("username" in user and "email" in user and "password" in user):
			return True
		else:
			return False

	def encode_auth_token(self):
		"""
		Generates the Auth Token
		:return: string
		"""
		try:
			header = {
				"alg": "HS256",
				"typ": "JWT"
			}
			# Max value = timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)
			payload = {
				"exp": datetime.utcnow() + timedelta(days=2, hours=0, minutes=0, seconds=0, microseconds=0),
				"iat": datetime.utcnow(),
				"sub": self.id,
				"name": self.username
			}
			return encode(payload, self.username, headers=header)
			#return "hshhdhdsjlhlfdjh"
		except Exception as e:
			return e

	@classmethod
	def get_users_by_filter(classname, filter):
		query = "select * from Users inner join seekerdetails on Users.id = Seekerdetails.user where "
		for key, value in filter.items():
			query = "{} Seekerdetails.{} = {}".format(query, key, value)
		print(query)
		result = db.engine.execute(query)
		list_result =[]
		for job in result:
			job_object = dict(zip(result.keys(), job))
			list_result.append(User.serialize_dict(job_object))

		return list_result

	def serialize(self):
		json_user = {
			"id": self.id,
			"Username": self.username,
			"Email": self.email,
			#"registered_on": str(self.registered_on),
			"Recruiter": self.isrecruiter,
			"Fullname": self.fullname(),
			"details" : [detail.serialize() for detail in self.details]

		}
		return json_user

############################################################################################
#All the functions to retrieve seeker details and update them
############################################################################################
	def update_user(self, details):
		db.session.add(self)
		db.session.add(details)
		db.session.commit()
Ejemplo n.º 5
0
class Medicine_Master(db.Model):
    med_id = db.Column(db.Integer, primary_key=True)
    med_name = db.Column(db.String(50), unique=True)
    quantity = db.Column(db.Integer)
    rate = db.Column(db.Integer)
    patient = db.relationship('Track_Medicines', backref='medicine', lazy=True)
Ejemplo n.º 6
0
class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(140), nullable=False, unique=True)
    email = db.Column(db.String(140), nullable=False, unique=True)
    password = db.Column(db.String(80), nullable=False)
    image = db.Column(db.String(120), default='default.jpg', nullable=False)
    resume = db.Column(db.String(120), default='default.pdf', nullable=False)

    # personal details
    name = db.Column(db.String(40))
    mobile = db.Column(db.String(14))
    phone = db.Column(db.String(14))
    dob = db.Column(db.String(20))
    address = db.Column(db.String(200))
    hobbies = db.Column(db.String(100))
    country = db.Column(db.String(30))
    city = db.Column(db.String(30))

    # for Messages
    messages_sent = db.relationship('Message',
                                    foreign_keys='Message.sender_id',
                                    backref='author',
                                    lazy='dynamic')
    messages_received = db.relationship('Message',
                                        foreign_keys='Message.recipient_id',
                                        backref='recipient',
                                        lazy='dynamic')
    last_message_read_time = db.Column(db.DateTime)

    notifications = db.relationship('Notification',
                                    backref='user',
                                    lazy='dynamic')

    # for resume
    resume_details = db.relationship('Resume',
                                     backref='resume_details',
                                     lazy='dynamic')

    # add notification
    def add_notification(self, name, data):
        self.notifications.filter_by(name=name).delete()
        n = Notification(name=name, payload_json=json.dumps(data), user=self)
        db.session.add(n)
        return n

    # for getting new Messages
    def new_messages(self):
        last_read_time = self.last_message_read_time or datetime(1900, 1, 1)
        return Message.query.filter_by(recipient=self).filter(
            Message.timestamp > last_read_time).count()

    # for password reset
    def get_reset_token(self, expires_in=600):
        return jwt.encode(
            {
                'reset_password': self.id,
                'exp': time() + expires_in
            },
            app.config['SECRET_KEY'],
            algorithm='HS256').decode('utf-8')

    @staticmethod
    def verify_reset_token(token):
        try:
            print(token)
            id = jwt.decode(token,
                            app.config['SECRET_KEY'],
                            algorithms=['HS256'])['reset_password']
        except:
            return None
        return User.query.get(id)

    def __repr__(self):
        return "{0.username} - {0.email}".format(self)