New to sqlalchemy.
I am trying to figure out how to best use query and filter to select a specific User based on entries under the created instance e.g. 'a.create_user('guy', 'Joe', 'Smo', ...) (as shown in a.retrieve_user(some username, ... some password) that I created for Users.
I created a class called BaseModify that I want to use to access the functions I have created to retrieve them based on the correct username/password combo; I also want to update them based on calling retrieve_user (which if correct) can then be updated. I tried the code below, but it prints out the user regardless of correct parameters which is very problematic. Any explanation of help is truly appreciated.
Create User works here... I've adjusted thanks to some help on here.
class BaseModify(object):
def __init__(self):
self.session = Session()
# Create User
def create_user(self, username, password, firstname, lastname):
new_user = User(username, password, firstname, lastname)
self.session.add(new_user)
self.session.commit()
print(username, firstname, lastname)
def retrieve_user(self, username, firstname, lastname):
users = self.session.query(User).\
filter(User.username == username).\
filter(User.firstname == firstname).\
filter(User.lastname == lastname).all()
for user in users:
print(user.username, user.firstname, user.lastname)
def update_user(self, username):
up = self.session.query(User).filter(User.username == username).first()
print up.username
if up:
up.username = username
new_username = up.username
return new_username
self.session.commit()
def delete_user(self, username, password):
deluser = self.retrieve_user(username, firstname, lastname)
if deluser:
self.session.query(User).filter(User.username == username).\
filter(User.firstname == firstname).\
filter(User.lastname == lastname)
self.session.delete(User)
self.session.flush()
""" instantiate (create) instances of the API below: """
a = BaseModify()
#create
a.create_user('dance', 'cats', 'Jas', 'Lo')
a.create_user('wizzard', 'linux', 'Bree', 'Jane')
a.retrieve_user('dance', 'cats')
a.retrieve_user('wizzard', 'dogs')
print(a)
I've made updates to the top. Trying to simply change the username through "update_user" and "delete_user" by calling the "retrieve" method to clean the code up. From what I understand, query/filter is to search through the tables and then the remainder of the code is python doing something. That right??? Best practices??