Bad Request Using Flask(<ast.Constant object at 0x0000027DDCB9ADD0>) - python

While Trying to insert data through Swagger UI API,
Input field I take:
{ "answer": 0, "choice1": "string", "choice2": "string",
"choice3": "string", "choice4": "string", "marks": 0, "qustion":
"string", "remarks": "string", "session_id":
"bca7d2ac-8264-47ca-9fa9-7c81e1bbaa79" }
This Error occur: <ast.Constant object at 0x0000027DDCB9ADD0>
Input taken through below code:
def add_questions(**kwargs):
try:
question = QuestionMaster(
uuid.uuid4(),
kwargs['question'],
kwargs['choice1'],
kwargs['choice2'],
kwargs['choice3'],
kwargs['choice4'],
kwargs['answer'],
kwargs['marks'],
kwargs['remarks']
)
db.session.add(question)
db.session.commit()
except Exception as e:
raise e
APi code:
class AddQuestionAPI(MethodResource, Resource):
#doc(description='Add Question API', tags=['Question'])
#use_kwargs(AddQustionRequest, location = ('json'))
#marshal_with(APIResponse)
def post(self, **kwargs):
try:
is_active, user_id = check_if_session_is_active(kwargs['session_id'])
if not is_active:
return APIResponse().dump(dict(message ='User is not logged in' )), 404
is_admin = check_if_admin(user_id)
if not is_admin:
return APIResponse().dump(dict(message ='User is not a Admin' )), 401
add_questions(**kwargs)
return APIResponse().dump(dict(message ='Qustion sucessfully added' )), 200
except Exception as e:
print(Str(e))
return APIResponse().dump(dict(message=f'Error in adding qustion: {str(e)}')), 400
api.add_resource(AddQuestionAPI, '/add.question')
docs.register(AddQuestionAPI)
DB Schema code:
class AddQustionRequest(Schema):
session_id = fields.Str(default="session_id")
qustion = fields.Str(default="question")
choice1 = fields.Str(default="choice1")
choice2 = fields.Str(default="choice2")
choice3 = fields.Str(default="choice3")
choice4 = fields.Str(default="choice4")
marks = fields.Int(default= 0)
remarks = fields.Str(default="remarks")
answer = fields.Int(default= 0)
DB Model Code:
class QuestionMaster(db.Model):
__tablename__ = 'question_master'
id = db.Column(db.String(100), primary_key=True)
question = db.Column(db.String(500), unique=True)
choice1 = db.Column(db.String(500))
choice2 = db.Column(db.String(500))
choice3 = db.Column(db.String(500))
choice4 = db.Column(db.String(500))
answer = db.Column(db.Integer)
marks = db.Column(db.Integer)
remarks = db.Column(db.String(200))
is_active = db.Column(db.Integer, default=1)
created_ts = db.Column(db.DateTime, default=datetime.utcnow())
updated_ts = db.Column(db.DateTime)
def __init__(self, id, question, choice1,
choice2, choice3, choice4, answer, marks, remarks):
self.id = id
self.question = question
self.choice1 = choice1
self.choice2 = choice2
self.choice2 = choice3
self.choice2 = choice4
self.answer = answer
self.marks = marks
self.remarks = remarks
self.is_active = 1
self.created_ts = datetime.utcnow()

Related

Login for different users not working in flask

So I've got a login form and I've got two user's in the users table one with a type student and the other is tutor. So when they log in it will take them to their own pages. But I've tested it but it doesn't work, it takes me to a page called None. So I want to know why it's doing this and what can I do to fix it??
Here is my code in the routes file:
def login():
if current_user.is_authenticated:
if type=="student":
return redirect(url_for('studentdashboard'))
elif type == "tutor":
return redirect(url_for('tutordashboard'))
elif type == "admin":
return redirect(url_for('admindashboard'))
form = LoginForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page= request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
if type=="student": next_page = url_for('studentdashboard')
elif type=='tutor': next_page = url_for('tutordashboard')
elif type=='admin': next_page = url_for('admindashboard')
return redirect(next_page)
return redirect(url_for('studentdashboard'))
return render_template('login.html', title='Sign In', form=form)
Here is my code in the models file :
class User(UserMixin,db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(50))
surname = db.Column(db.String(50))
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
address = db.Column(db.String(100))
town = db.Column(db.String(100))
city = db.Column(db.String(100))
postcode = db.Column(db.String(7))
phone = db.Column(db.String(11))
workexperience = db.Column(db.String(100))
is_active = db.Column(db.Boolean,default=False)
type = db.Column(db.String(20))
def
__init__ (self, firstname, surname, username, email, password_hash, address, town, city,
postcode, phone,workexperience,is_active,type):
self.firstname = firstname
self.surname = surname
self.username = username
self.email = email
self.password_hash = password_hash
self.address = address
self.town = town
self.city = city
self.postcode = postcode
self.phone = phone
self.workexperience = workexperience
self.is_active = is_active
self.type = type
def get_id(self):
return self.id
def is_active(self):
return self.is_active
def activate_user(self):
self.is_active = True
def get_username(self):
return self.username
def get_type(self):
return self.type
def login_required(role="ANY"):
def wrapper(fn):
#wraps(fn)
def decorated_view(*args, **kwargs):
if not current_user.is_authenticated():
return login_manager.unauthorized()
if ((current_user.type != type) and (type != "ANY")):
return login_manager.unauthorized()
return fn(*args, **kwargs)
return decorated_view
return wrapper
Here is the error: enter image description here

AttributeError: type object 'Auth' has no attribute 'query'

So I've been using this method for a few projects now but for some reason I'm getting an error.
Code involved:
class Auth(db.Column):
__tablename__ = 'ezauth'
id = db.Column(db.Integer, primary_key=True, nullable=False)
username = db.Column(db.String, nullable=False)
email = db.Column(db.String, nullable=False)
password = db.Column(db.String, nullable=False)
confirmed = db.Column(db.Boolean, nullable=False, default=False)
def __repr__(self):
return f"Auth(username='{self.username}', email='{self.email}', password='{self.password}'"
and
#app.route('/api/login', methods=['POST'])
def apilogin():
if request.method == 'POST':
email = request.form.get('email')
password = request.form.get('password')
if email != None and password != None:
value1 = Auth.query.filter_by(email=email).first()
if value1 != None:
db_pass = value1.password
oid = value1.id
if sha256_crypt.verify(str(password), db_pass):
token = create_token()
tokendb = Token(token=token, oid=oid)
return Response('{"success": true, "message": "Logged in", "token": "' + str(token) + '"}', status=200, mimetype='application/json')
else:
return Response('{"success": false, "message": "Incorrect password"}', status=400, mimetype='application/json')
else:
return Response('{"success": false, "message": "Email not registered"}', status=400, mimetype='application/json')
else:
return Response('{"success": false, "message": "Wrong form parameters"}', status=400, mimetype='application/json')
But, the Auth.query.all() (or any other variation on Auth.query) doesn't work for some reason, it returns the AttributeError: type object 'Auth' has no attribute 'query' error. It has worked in previous projects, just not this one.

Flask SQLAlchemy - not updating, just adding a new record

I'm writing a simple app for adding and updating information to sqlite3 database using Flask-SQLAlchemy. Now I have a big problem, because I cannot update the database, it just adds a new record every time I submit the form button.
Here is my code:
#main.route("/invoices", methods=["GET", "POST"], defaults={"invoice_id": None})
#main.route("/invoices/<int:invoice_id>", methods=["GET", "POST"])
def invoices(invoice_id):
invoice = None
if invoice_id:
invoice = Invoice.query.get_or_404(invoice_id)
if request.method == "POST":
date = request.form["date"]
name = request.form["name"]
value = request.form["value"]
currency = request.form["currency"]
payment = request.form["payment"]
category = request.form["category"]
description = request.form["description"]
if invoice:
invoice.date = datetime.strptime(date, "%Y-%m-%d")
invoice.name = name
invoice.value = value
invoice.currency = currency
invoice.payment = payment
invoice.category = category
invoice.description = description
else:
invoice = Invoice(
date=datetime.strptime(date, "%Y-%m-%d"),
name=name,
value=value,
currency=currency,
payment=payment,
category=category,
description=description,
)
db.session.add(invoice)
db.session.commit()
return redirect(url_for("main.invoices", invoice_id=invoice.id))
currencies = Currency.query.all()
payments = Payment.query.all()
categories = Category.query.all()
context = {
"invoice_id": invoice_id,
"currencies": currencies,
"payments": payments,
"categories": categories,
"invoice": invoice,
}
return render_template("invoices.html", **context)
I don't know how to update the data, because it always adds a new record, now just commits the existing or changed fields. Maybe something wrong is with my if statements...
Please help me with this task...
Here is the models:
class Invoice(db.Model):
id = db.Column(db.Integer, primary_key=True)
value = db.Column(db.Integer)
date = db.Column(db.DateTime)
name = db.Column(db.String(50))
description = db.Column(db.String(100))
currency = db.Column(db.ForeignKey("currency.id"))
payment = db.Column(db.ForeignKey("payment.id"))
category = db.Column(db.ForeignKey("category.id"))
class Currency(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(10))
class Payment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
This code may be help to you
#main.route("/invoices", methods=["GET", "POST"], defaults={"invoice_id": None})
#main.route("/invoices/<int:invoice_id>", methods=["GET", "POST"])
def invoices(invoice_id):
invoice = None
if invoice_id is not None:
invoice = Invoice.query.filter_by(id=invoice_id).first()
if request.method == "POST":
date = request.form["date"]
name = request.form["name"]
value = request.form["value"]
currency = request.form["currency"]
payment = request.form["payment"]
category = request.form["category"]
description = request.form["description"]
if invoice is not None:
invoice.date = datetime.strptime(date, "%Y-%m-%d")
invoice.name = name
invoice.value = value
invoice.currency = currency
invoice.payment = payment
invoice.category = category
invoice.description = description
else:
invoice = Invoice(
date=datetime.strptime(date, "%Y-%m-%d"),
name=name,
value=value,
currency=currency,
payment=payment,
category=category,
description=description,
)
db.session.add(invoice)
db.session.commit()
return redirect(url_for("main.invoices", invoice_id=invoice.id))
currencies = Currency.query.all()
payments = Payment.query.all()
categories = Category.query.all()
context = {
"invoice_id": invoice_id,
"currencies": currencies,
"payments": payments,
"categories": categories,
"invoice": invoice,
}
return render_template("invoices.html", **context)

Python flask TypeError: unsupported operand type(s) for |: 'bool' and 'BinaryExpression'

I'm trying to send a put request to update student tags however I am getting a type error on my on my local machine using postman, I believe it is something to do with the email in the student services but I am not to sure why. Help would be greatly appreciated as I am quite new to python, thanks!
Console:
File "/Users/thomashunt/projects/ct-platform-api/apis/student_api.py", line 519, in put
return StudentService.student_ldi_attendees(submission)
File "/Users/thomashunt/projects/ct-platform-api/services/students.py", line 237, in student_ldi_attendees
student = repo.find_by_email(Person.email)
File "/Users/thomashunt/projects/ct-platform-api/services/database/person_data.py", line 27, in find_by_email
return self.session.query(self.person_user).filter((Person.email == email) | (Person.alt_email == email)).first()
TypeError: unsupported operand type(s) for |: 'bool' and 'BinaryExpression'
ct platform API
#ns.route('/student-ldi-attendees')
class studentldiattendeesEndpoint(Resource):
#SecurityService.requires_system
#ns.expect(student_ldi_attendees_model, validate=True)
#ns.marshal_with(student_person_model)
def put(self):
logging.info('student LDI 2019 tag appended')
submission = studentldiattendees.from_dict(request.json)
return StudentService.student_ldi_attendees(submission)
Services students
#staticmethod
def student_ldi_attendees(submission: studentldiattendees ) -> Person:
repo = PersonData()
# advisor = repo.find_by_email(submission.advisor_email)
email = submission.email.lower()
student = repo.find_by_email(Person.email)
if not student:
raise RecordNotFoundException('No Record with this email in the database')
submission.set_model(Person)
Person.student_detail.student_tags = submission.student_tags
repo.session.commit()
return student
person_data.py
class PersonData(BaseRepository):
person_user = with_polymorphic(Person, '*')
def find_by_id_list(self, id_list: List[str]) -> List[Person]:
return self.session.query(self.person_user).filter(Person.id.in_(id_list)).all()
def load(self, person_id: str) -> Person:
return self.session.query(self.person_user).filter(Person.id == person_id).first()
def list(self, page: int=1, page_size: int=100):
page_query = self.session.query(self.person_user).paginate(page=page, per_page=page_size,
max_per_page=page_size,
error_out=False)
return page_query.items
//line 27 below
def find_by_email(self, email: str) -> Person:
return self.session.query(self.person_user).filter((Person.email == email) | (Person.alt_email == email)).first()
def save(self, data: Person, by_user_id: str = None) -> Person:
if data.id is None:
data.id = uuid.uuid4()
data.created_by_user_id = by_user_id
data.date_created = datetime.utcnow()
else:
if data.contact_detail and data.contact_detail.location_address:
flag_modified(data.contact_detail, 'location_address')
if data.student_detail and data.student_detail.location_address:
flag_modified(data.student_detail, 'location_address')
data.date_updated = data.date_updated or datetime.utcnow()
data.updated_by_user_id = by_user_id or data.updated_by_user_id
self.session.add(data)
return data
def delete(self, data: Person):
self.session.delete(data)
studentldiattendees model:
class studentldiattendees(object):
def __init__(self):
self.first_name = None
self.last_name = None
self.email = None
self.student_tags: List[str] = None
def set_model(self, model: Person):
model.student_tags = self.student_tags
# if self.student_tags:
# TagsEdit.set_model(self, model)
# else:
# model.student_tags = []
model.first_name = self.first_name
model.last_name = self.last_name
model.email = self.email
#staticmethod
def from_dict(dct):
print(dct)
entity = studentldiattendees()
entity.first_name = dct.get('first_name')
entity.last_name = dct.get('last_name')
entity.email = dct.get('email')
entity.student_tags = TagsEdit.from_dict(dct.get('student_tags'))
return entity
Class Person
class Person(db.Model):
tablename = 'person'
id = db.Column(db_ext.UUID(as_uuid=True), primary_key=True, server_default=sa_text("uuid_generate_v4()"))
person_number = db.Column(db.Integer, db.Sequence('person_number_sequence'))
date_created = db.Column(db.DateTime)
date_updated = db.Column(db.DateTime)
created_by_user_id = db.Column(db_ext.UUID(as_uuid=True))
updated_by_user_id = db.Column(db_ext.UUID(as_uuid=True))
first_name = db.Column(db.String(30))
birth_name = db.Column(db.String(30)) # If different to preferred (first) name
middle_name = db.Column(db.String(30))
last_name = db.Column(db.String(30))
email = db.Column(db.String(150))
alt_email = db.Column(db.String(150))
phone_numbers = db.Column(PhoneListDecorator)
facebook_url = db.Column(db.Text(length=150))
linkedin_url = db.Column(db.Text(length=150))
twitter_url = db.Column(db.Text(length=150))
instagram_url = db.Column(db.Text(length=150))
gender = db.Column(db.String(10))
is_advisor = db.Column(db.Boolean)
is_client = db.Column(db.Boolean)
is_student = db.Column(db.Boolean)
is_deleted = db.Column(db.Boolean)
deleted_by_person_id = db.Column(db.Text)
date_deleted = db.Column(db.DateTime)
is_no_contact = db.Column(db.Boolean)
set_no_contact_by_user_id = db.Column(db.String)
student_detail = db.relationship("Student", uselist=False, lazy='joined')
contact_detail = db.relationship("Contact", uselist=False, lazy='joined')
person_user = db.Column(db.Text)
__mapper_args__ = {
'polymorphic_identity': 'person',
'polymorphic_on': person_user,
'with_polymorphic': '*'
}
def __init__(self):
"""
Initialise object props we want to manage together. Do not need to do all props
such as child sets and can let the database manage those
"""
self.id: str = None
self.date_created: datetime = None
self.date_updated: datetime = None
self.created_by_user_id: str = None
self.updated_by_user_id: str = None
self.first_name: str = None
self.birth_name: str = None
self.last_name: str = None
self.middle_name: str = None
self.email: str = None
self.alt_email: str = None
self.phone_numbers: List[PhoneNumber] = []
self.facebook_url: str = None
self.linkedin_url: str = None
self.twitter_url: str = None
self.instagram_url: str = None
self.gender: str = None
self.is_advisor: bool = False
self.is_client: bool = False
self.is_student: bool = False
self.is_deleted: bool = False
self.deleted_by_person_id: str = None
self.is_no_contact: bool = False
self.set_no_contact_by_user_id: str = None
self.student_detail: Student = None
self.contact_detail: Contact = None
def get_formatted_name(self):
name_parts = self.get_name_parts()
if len(name_parts) == 0:
return "Unknown Person"
else:
return " ".join(name_parts)
def get_name_parts(self):
name_parts = []
if self.first_name:
name_parts.append(self.first_name)
if self.birth_name and self.birth_name != self.first_name:
name_parts.append("({0})".format(self.birth_name))
if self.last_name:
name_parts.append(self.last_name)
return name_parts

Using python library flask-rest-jsonapi without id as primary key

I am using Python library flask-rest-jsonapi to design an API. The library uses flask-sqlalchemy and marshmallow. Marshmallow has a requirement to have an "id" and a "type" field mandatory in the schema.
The database tables that I am designing APIs for doesn't have "id" column. The two tables that I am trying to define the relationship are called Department and Teacher where one department has multiple teachers so there is one to many relationship between department and teacher. Their primary keys columns are called "Department_Unique_ID" and "Teacher_Unique_ID".
Here is my code:
from flask import Flask
from flask_rest_jsonapi import Api, ResourceDetail, ResourceList, ResourceRelationship
from flask_rest_jsonapi.exceptions import ObjectNotFound
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
from marshmallow_jsonapi.flask import Schema, Relationship
from marshmallow_jsonapi import fields
import connectDB
# Create the Flask application
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app = connectDB.connectToDb(app)
db = SQLAlchemy(app)
class Department(db.Model):
db.Model.metadata.schema = 'UNIVERSITY'
__tablename__ = 'Department'
Department_Unique_ID = db.Column(db.String, primary_key=True)
Department_Name = db.Column(db.String)
uni_teacher = db.relationship('Teacher', backref=db.backref('Department'))
__mapper_args__ = {
"order_by":Department_Unique_ID
}
class Teacher(db.Model):
db.Model.metadata.schema = 'UNIVERSITY'
__tablename__ = 'Teacher'
Teacher_Unique_ID = db.Column(db.String, primary_key=True)
Teacher_Name = db.Column(db.String)
Department_ID_Unique = db.Column(db.String, db.ForeignKey('Department.Department_Unique_ID'))
__mapper_args__ = {
"order_by":Teacher_Unique_ID
}
class DepartmentSchema(Schema):
class Meta:
type_ = 'uni_department'
self_view = 'uni_department_detail'
self_view_kwargs = {'id': '<Department_Unique_ID>'}
self_view_many = 'uni_department_list'
strict = True
__model__ = Department
id = fields.Integer(as_string=True, many=True, dump_only=True) #not used, if I remove this, I get an error "Must have an 'id' field"
Department_Unique_ID = fields.Str()
Department_Name = fields.Str()
uni_teacher = Relationship(self_view='uni_department_uni_teacher',
self_view_kwargs={'id':'<Department_Unique_ID>'},
related_view='uni_teacher_list',
related_view_kwargs={'id':'<Department_Unique_ID>'},
many=True,
schema='TeacherSchema',
type_='uni_teacher',
id_field='Teacher_Unique_ID')
class TeacherSchema(Schema):
class Meta:
type_ = 'uni_teacher'
self_view = 'uni_teacher_detail'
self_view_kwargs = {'id': '<Teacher_Unique_ID>'}
self_view_many = 'uni_teacher_list'
strict = True
__model__ = Teacher
id = fields.Integer(as_string=True, many=True, dump_only=True) #not used, if I remove this, I get an error "Must have an 'id' field"
Teacher_Unique_ID = fields.Str()
Teacher_Name = fields.Str()
owner = Relationship(attribute='uni_department',
self_view='uni_teacher_uni_department',
self_view_kwargs={'id':'<Teacher_Unique_ID>'},
related_view='uni_department_detail',
related_view_kwargs={'id':'<Department_Unique_ID>'},
schema='DepartmentSchema',
type_='uni_department')
class DepartmentList(ResourceList):
schema = DepartmentSchema
data_layer = {'session': db.session,
'model': Department}
class TeacherList(ResourceList):
def query(self, view_kwargs):
query_ = self.session.query(Teacher)
if view_kwargs.get('Teacher_Unique_ID') is not None:
try:
self.session.query(Department).filter_by(Teacher_Unique_ID=view_kwargs['Teacher_Unique_ID']).one()
except NoResultFound:
raise ObjectNotFound({'parameter': 'Teacher_Unique_ID'}, "Teacher: {} not found".format(view_kwargs['Teacher_Unique_ID']))
else:
query_ = query_.join(Department).filter(Department.id == view_kwargs['Teacher_Unique_ID'])
return query_
def before_create_object(self, data, view_kwargs):
if view_kwargs.get('Teacher_Unique_ID') is not None:
uni_department = self.session.query(Department).filter_by(Teacher_Unique_ID=view_kwargs['Department_Unique_ID']).one()
data['Department_Unique_ID'] = uni_department.Department_Unique_ID
schema = TeacherSchema
data_layer = {'session': db.session,
'model': Teacher}
class DepartmentDetail(ResourceDetail):
def before_get_object(self, view_kwargs):
if view_kwargs.get('Teacher_Unique_ID') is not None:
try:
uni_teacher = self.session.query(Teacher).filter_by(Department_Unique_ID=view_kwargs['Department_Unique_ID']).one()
except NoResultFound:
raise ObjectNotFound({'parameter': 'Department_Unique_ID'},
"Teacher: {} not found".format(view_kwargs['Department_Unique_ID']))
else:
if uni_teacher.uni_department is not None:
view_kwargs['Department_Unique_ID'] = uni_teacher.uni_department.Department_Unique_ID
else:
view_kwargs['Department_Unique_ID'] = None
schema = DepartmentSchema
data_layer = {'session': db.session,
'model': Department}
class TeacherDetail(ResourceDetail):
schema = TeacherSchema
data_layer = {'session': db.session,
'model': Teacher}
class DepartmentRelationship(ResourceRelationship):
schema = DepartmentSchema
data_layer = {'session': db.session,
'model': Department}
class TeacherRelationship(ResourceRelationship):
schema = TeacherSchema
data_layer = {'session': db.session,
'model': Teacher}
api = Api(app)
api.route(DepartmentList, 'uni_department_list', '/uni_department')
api.route(TeacherList, 'uni_teacher_list', '/uni_teacher', '/uni_teacher/<int:Department_Unique_ID>/uni_teacher')
api.route(DepartmentDetail, 'uni_department_detail', '/uni_department/<int:Department_Unique_ID>', '/uni_teacher/<int:Department_ID_Unique>/owner')
api.route(TeacherDetail, 'uni_teacher_detail', '/uni_teacher/<int:Teacher_Unique_ID>')
api.route(DepartmentRelationship, 'uni_department_uni_teacher', '/uni_department/<int:Department_Unique_ID>/relationships/uni_teacher')
api.route(TeacherRelationship, 'uni_teacher_uni_department', '/uni_teacher/<int:Teacher_Unique_Department>/relationships/owner')
if __name__ == '__main__':
# Start application
app.debug = True
app.run()
I am following the example from flask-rest-jsonapi. Any help would be appreciated.
EDIT1- Here is the connectDB.py code as requested-
import yaml
def readDbDetails():
with open('database_config.yaml', 'r') as stream:
return (yaml.load(stream))
dbDetails = readDbDetails()
def connectToDb(app):
database_host = dbDetails['database_host']
database_username = dbDetails['database_username']
database_name = dbDetails['database_name']
database_password = dbDetails['database_password']
database_port = dbDetails['database_port']
print(database_host)
print(database_name)
print(database_username)
print(database_password)
print(database_port)
app.config[
'SQLALCHEMY_DATABASE_URI'] = 'mssql+pymssql://'+database_username+':'+database_password+'#'+database_host+':'+database_port+'/'+database_name+''
return app
You can use attribute property and assign the primary key to that id field
class DepartmentSchema(Schema):
class Meta:
type_ = 'uni_department'
self_view = 'uni_department_detail'
self_view_kwargs = {'id': '<Department_Unique_ID>'}
self_view_many = 'uni_department_list'
strict = True
__model__ = Department
id = fields.Integer(attribute='Department_Unique_ID', as_string=True, many=True, dump_only=True)
Department_Unique_ID = fields.Str()
Department_Name = fields.Str()
uni_teacher = Relationship(self_view='uni_department_uni_teacher',
self_view_kwargs={'id': '<Department_Unique_ID>'},
related_view='uni_teacher_list',
related_view_kwargs={'id': '<Department_Unique_ID>'},
many=True,
schema='TeacherSchema',
type_='uni_teacher',
id_field='Teacher_Unique_ID')
class TeacherSchema(Schema):
class Meta:
type_ = 'uni_teacher'
self_view = 'uni_teacher_detail'
self_view_kwargs = {'id': '<Teacher_Unique_ID>'}
self_view_many = 'uni_teacher_list'
strict = True
__model__ = Teacher
id = fields.Integer(attribute='Teacher_Unique_ID', as_string=True, many=True, dump_only=True)
Teacher_Unique_ID = fields.Str()
Teacher_Name = fields.Str()
owner = Relationship(attribute='uni_department',
self_view='uni_teacher_uni_department',
self_view_kwargs={'id': '<Teacher_Unique_ID>'},
related_view='uni_department_detail',
related_view_kwargs={'id': '<Department_Unique_ID>'},
schema='DepartmentSchema',
type_='uni_department')

Categories

Resources