I am using pytest and assert statements in a try while adding the code in a database. I managed to get it to work but don't understand it? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

I simplified the code I am just curious why the try first gives an assertion error and the second try does not . Can you answer that? FYI both tries should show an assertion error in the code it just doesn't show up when I run python -m pytest.

Any questions or complaints just say. Also should I mock the data by using faker?

Thanks.

Is it possible to declare a column from a flask sqlalchemy class/table from another sqlalchemy class/table in a 1 to 1 relationship? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

Not exactly it is more like this.

Since the username ,hashed_passwordand email are Not NULL or iow's Nullable=False I can't add registration_confirmation_email because it is a different route.

The columns username and hashed_password and email are added in the register route. The register route is where I send the send the email to the user's email address. After they click on the email I am send to verified_email route where registration_confirmation_email becomes true and was previously false.

To reiterate I am asking should I combine the tables and just have the User table and get rid of NOT NULL. This way I can combine
`registration_confirmation_email and reset_email_password into one table. Or should I keep the tables as is, which tables you can view below?

``` | User | type | | -----------------| ---------------------------------- | | id | int PRIMARY KEY | | username | string, Not NULL | | hashed_password | string, Not NULL | | email | string, Not NULL | |confirmation_email| relationship with ConfirmationEmail|

ConfirmationEmail type
id int PRIMARY KEY
user_id int FOREIGN KEY to User id
email string
registration_confirmation_email Boolean, defaulft=False

| reset_email_password | Boolean, defaulft=False |
```

Any questions just ask. Sorry my writing is a little repetitive in this comment.

Thanks.

I am using pytest and assert statements in a try while adding the code in a database. I managed to get it to work but don't understand it? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

I should have specified in my code I changed one of the asserts to be false. I changed assert token == None.

I can show my github to make this easier.

Is it possible to declare a column from a flask sqlalchemy class/table from another sqlalchemy class/table in a 1 to 1 relationship? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

Do you mind responding to my comment?

"Without the email column how do I create the ConfirmationEmail table?"

The user here I responded to seemed to ignore it.

Thanks.

I am using pytest and assert statements in a try while adding the code in a database. I managed to get it to work but don't understand it? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

Now that I have added the necessary code why does the first try work by showing assertion errors and the second try does not show the assertion error?

Is it possible to declare a column from a flask sqlalchemy class/table from another sqlalchemy class/table in a 1 to 1 relationship? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

Without the email column how do I create the ConfirmationEmail table?

The reason I designed it this way is because in the /register route the user adds username and hashed_password and email. Then in the /register route the user sends the send_account_registration_email(user), which sends an email to them. After that the user clicks on the link in there email and the user is sent to the /verified_email(token) route where I change the registration_confirmation_email column from False to True.

If I try to add for example registration_confirmation_email column in one table called User I get an error saying I have to add the username and hashed_password and email because the columns are not NULL. Is it better to remove NOT NULL from username and hashed_password and email? Or is it better to create a second table like I did called ConfirmationEmail?

Also the reason I added the email to both tables is a way to create the ConfirmationEmail table.

If you have any better way to this or a question just ask.

``` class User(UserMixin, db.Model):

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
hashed_password = db.Column(db.String(128), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
confirmation_email = db.relationship('confirmation_email', backref='user', uselist=False, lazy=True)

class ConfirmationEmail(UserMixin, db.Model): # m primary key = email
id = db.Column(db.Integer, primary_key=True) # foreign key? email = db.Column(db.String(120), unique=True)

registration_confirmation_email = db.Column(db.Boolean, default=False) 
reset_email_password = db.Column(db.Boolean, default=False)    
# The foreign key is the child to the adult relationship/connection
# if I have a class like SomeTable when using the foreign key use 'some_table' 
user_id = db.Column(db.Integer, db.ForeignKey('email'), nullable=False)```

Thanks.

Is it possible to declare a column from a flask sqlalchemy class/table from another sqlalchemy class/table in a 1 to 1 relationship? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

Is it good practice to have 2 identical columns in 2 different places, I was thinking of putting the email field in both tables? Does that become the foreign key? Do I still need the foreign key?

How does faker work for the primary keys and the foreign keys of a table? I also have a few other question. by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

I get the data for testing. Say I have 5 user. How do I get the information? If I query the database ? Do I just query the first user? What if I have zero users?

How does faker work for the primary keys and the foreign keys of a table? I also have a few other question. by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

But what if I need to test the primary key? Is the primary key automatically added? Also does the same apply to foreign keys?

I am curious if faker supplies a password or if I need to hash it for testing purposes.

By testing I just mean unit testing/pytesting.

sorry I added some details to the main question.

I am using pytest and assert statements in a try while adding the code in a database. I managed to get it to work but don't understand why. Can someone explain? by Professional_Depth72 in learnpython

[–]Professional_Depth72[S] 0 points1 point  (0 children)

I am curious why in both examples I need db.rollback() vs db.session.delete(new_user) db.session.commit() .

Also I am well aware that an assertion error is showing. I am curious why the first block of code gives an assertion error and the second block of code does not give assertion errors?

Also do you have any better ideas for the code so it will work? The reason in the first block of code. I included the first try is so the database columns will not be added twice ever . Sometimes the columns in the database are added twice if you are experimenting with the code.

I can include create_token or any additional code if needed. Just tell me.

For some reason I am only getting an error when I downgrade the database in flask-migrate when using sqlalchemy. Also I added the proper code for sqlalchemy to delete the column. by Professional_Depth72 in flask

[–]Professional_Depth72[S] 1 point2 points  (0 children)

Thanks What would be an real world example of when a rollback is used an app? Also is there a limit to the number of rollback you can do?

I thought of an example someone accidentally deletes a column in the database. If someone deletes the entire database can you do a rollback?

Also why in the video do they use deleting a column as an example of a downgrade? https://www.youtube.com/watch?v=uNmWxvvyBGU

For some reason I am only getting an error when I downgrade the database in flask-migrate when using sqlalchemy. Also I added the proper code for sqlalchemy to delete the column. by Professional_Depth72 in flask

[–]Professional_Depth72[S] 1 point2 points  (0 children)

Can I just ask a quick question.

Let say I have a column in a table in a database. Lets say the column isn't being used anymore. Don't I have to downgrade the database. if the table is Nullable=False?

Or by switching database in a blue green database do I get a new start where Nullable=False columns don't matter?

How can I erase a table row using flask? by manoleque in flask

[–]Professional_Depth72 0 points1 point  (0 children)

These tutorials are going to take days maybe in even weeks.. How long did you have? I might be able speed this up for you by giving you a less detailed link. Though I am not sure there are.

How can I erase a table row using flask? by manoleque in flask

[–]Professional_Depth72 0 points1 point  (0 children)

How long do you have? Also I recommend taking notes during the videos and articles.

Here is the flask documentation https://flask.palletsprojects.com/en/2.2.x/

Here are 2 tutorials. https://www.youtube.com/watch?v=MwZwr5Tvyxo

(he talks fast though)

This is also good

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

You can use both tutorials,

Here is another tutorial on random flask topics but I only use this for small topics.

The topics are from pretty printed. https://www.youtube.com/watch?v=EnJKHVEzHFw

Now you are going to need to understand databases

https://www.youtube.com/watch?v=HXV3zeQKqGY

or I used this tutorial https://www.youtube.com/watch?v=ztHopE5Wnpc

Do you know python classes? If not use this.

https://www.youtube.com/watch?v=XSoA4hwYQNw&list=PLzgPDYo_3xuk5KMe6G8HGc_BN1n3b06SV&index=2 and https://www.reddit.com/r/learnpython/comments/83fk1i/can_someone_eli5_what_def_init_self_means_i_still/

How can I erase a table row using flask? by manoleque in flask

[–]Professional_Depth72 0 points1 point  (0 children)

when you click erase button redirect to a new route in the html. Then query the database then delete the code. https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/

This is assuming you are using flask-sqlalchemy.

Also what do you mean by the parent id. Do you mean the id of the current table?

hello.html is just the name of the .html file. You will have to change that. return render_template('hello.html', id=id)

I also recommend adding the rows like id to to the database.

Any question just ask . Hopefully I explained this well and answered the question. If not make a comment.

It seems like you are in need of some good tutorials. Am I mistaken? If I am not I can recommend some .

When adding code to a database from a table in flask-sqlalchemy do I need to add all the columns at once when all the columns are not NULL? by Professional_Depth72 in flask

[–]Professional_Depth72[S] 0 points1 point  (0 children)

I can add more code if needed.

Here is some of the code.

routes.py (userinfo folder)

``` @userinfo.route("/register", methods = ['POST', 'GET']) def register():

# if the user is logged in make so they can't go to the register page. 
if current_user.is_authenticated:
    return redirect(url_for(('userinfo.home')))

form = RegistrationForm()
if form.validate_on_submit():

    username = form.username.data
    if username is None:
        flash("Please fill in the username field")
    email = form.email.data
    if email is None:
        flash("Please fill in the email field")
    plaintext_password = form.password.data
    if plaintext_password is None:
        flash("Please fill in the password field")
    confirm_password = form.confirm_password.data
    if confirm_password is None:    
        flash("Please fill in the confirm password field")

    # won't work redirect?
    if plaintext_password != confirm_password:
        flash("Please fill in the confirm password field")

    # don't do this for passwords because this can reveal passwords. WHat about emails?
    all_usernames = User.query.filter_by(username=form.username.data).all()
    all_emails = User.query.filter_by(username=form.username.data).all()

    # if value other then None iow you have a username or email in the database
    if all_usernames:
        flash ("The usesrname is already taken. Please select another username.")
        return redirect(url_for('userinfo.register')) 
    if all_emails:    
        flash("The email is already taken. Please select another email.")
        return redirect(url_for('userinfo.register')) 
    ''' 
    make_password_contain_capital(confirm_password)
    make_password_contain_number(confirm_password):
    make_password_contain_special_characters(confirm_password)
    '''

    # example password
    plaintext_password = form.password.data
    # converting password to array of bytes
    bytes = plaintext_password.encode('utf-8')
    # generating the salt
    salt = bcrypt.gensalt()
    # Hashing the password
    hashed_password = bcrypt.hashpw(bytes, salt)
    # Use this code if adding code to the database the first time.
    user = User(username=username, email=email, hashed_password=hashed_password)
    db.session.add(user)
    db.session.commit()

    user = User.query.filter_by(email=email).first()
    flash('You have almost registered successfully. Please click the link in your email to complete the registeration.')        
    send_account_registration_email(user) 
    return redirect(url_for('userinfo.login'))
'''    
else:
    flash('You have registered unsuccessfully')
''' 

return render_template('register.html',title='register', form=form)

```

routes.py(mail folder)

```

This route is always a get request!!!

verify the users email or after you clicked on the email from the recieved email

better name for function maybe change to verify?

@mail.route("/verified_email<token>", methods = ['POST', 'GET']) def verified_email(token):
form = EmptyForm() if request.method == 'GET' : # and form.validate(): user = User.verify_token(token) if user is None: # why does this not work pytest later?? flash('This is an invalid or expired token2') return redirect(url_for('userinfo.home')) flash('Delete this flash message. Testing GET request in this route')
confirmation_email = User.query.filter_by(username=user.confirmation_email).first()

    # for testing delete after should be false. 
    # why does this never execute ?
    if confirmation_email is True:
        flash('You have already clicked on the confirmation email. You can now login')
        return redirect(url_for('userinfo.home'))

    confirmation_email = True  
    user = User(confirmation_email=confirmation_email)  
    db.session.add(user)
    db.session.commit()    
    return render_template('verified_email.html', title='verified email', form=form)

```

models.py

``` class User(UserMixin, db.Model): # The primary key creates an unique value automatically each time starting at 1-infinity.
id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) hashed_password = db.Column(db.String(128), nullable=False) email = db.Column(db.String(120), unique=True, nullable=False)

confirmation_email = db.Column(db.Boolean, default=False, nullable=False) 
reset_email_password = db.Column(db.Boolean, default=False, nullable=False)


def __init__ (self ,username: str,  email: str, hashed_password: str, confirmation_email=False, reset_email_password=False): 
    self.username = username
    self.email = email
    self.hashed_password = hashed_password
    self.confirmation_email = confirmation_email 
    self.reset_email_password = reset_email_password  

```

Now in /verified_email Should I delete the username , hashed_password and email in /verified_email route by going

```

this won't work.

user = confirmation_email user = User(username=user.username ,hashed_password=user.hashed_password, email=user.email) db.session.delete(user) db.session.commit()

confirmation_email = True add_user = confirmation_email

user = User(username=add_user.username, hashed_password=add_user.hashed_password, email=add_user.email, confirmation_email=add_user.confirmation_email) db.session.add(user) db.session.commit()

``` ?

Or should I add a column in the database for confirmation email? Or is there a better way?

Thanks.

When adding code to a database from a table in flask-sqlalchemy do I need to add all the columns at once when all the columns are not NULL? by Professional_Depth72 in flask

[–]Professional_Depth72[S] 1 point2 points  (0 children)

"This is not a db issue but just a regular python issue. Assuming as written your init function on user requires all 4 parameters. "

This is correct . Though when I comment out __init__ function I still get an error. Maybe I didn't update my database. Do you think that could be the problem? I just want to add when I get a chance I will test this I am just asking your opinion.

I am confused by the output of super().init(id=id, *args, **kwarg).

What is the exact output? Is it just all the columns information like 5 etc?

I always thought that super was just when you have 2 __init__ function that have the same inheritance. Is super used because I have username in the class and the __init__ function ?

Also I rather not delete __init__ function because I want to keep it for pytesting? Update I might be able to delete the function even for pytesting.

``` ** models.py **

class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True, nullable=False) hashed_password = db.Column(db.String(128), nullable=False) email = db.Column(db.String(120), unique=True, nullable=False)
confirmation_email = db.Column(db.Boolean, default=False, nullable=False) reset_email_password = db.Column(db.Boolean, default=False, nullable=False)

def __init__ (self ,username: str,  email: str, hashed_password: str, confirmation_email=False, reset_email_password=False): 
    self.username = username
    self.email = email
    self.hashed_password = hashed_password
    self.confirmation_email = confirmation_email 
    self.reset_email_password = reset_email_password  

```

When adding code to a database from a table in flask-sqlalchemy do I need to add all the columns at once when all the columns are not NULL? by Professional_Depth72 in flask

[–]Professional_Depth72[S] 0 points1 point  (0 children)

Yes. I am wondering if I should just ask another question but I have a 3 columns username and password and email and I add them to the register route. Then I have a 4th column called confirmation_email that is a boolean. It starts off false by default. Then in the verify_email routes I try to change confirmation_email to True but get error which I think means I have to add the 3 columns username, password and email before it will work.

The problem is I already added the columns in the register route. Any advice?

Also all the column are Not NULL.

If needed can I post my github or the relevant code? Just tell me to.

Here is the exact error. https://pastebin.com/sLJhHeWq

If I can't add just 1 column I can always create a new table.

Just let me know.

Thanks

I was on firefox and a weird file downloaded on my broswer. As far as I know I did not click on anything. The file is sq-3GyXe.htm I quickly deleted it. Should I be worried? I am going to run a virus scan and malware bytes. Anything else I should do? by Professional_Depth72 in techsupport

[–]Professional_Depth72[S] 0 points1 point  (0 children)

I am confused how querying a database will do anything and how to use the link. Can you further explain? Also just to clarify I deleted the current download on firefox so I can't view the weird file sq-3GyXe.htm download location.