Forums

suggestions for adding a user to users table from flask_app.py -Beginner Guides Part2

Hi all,

https://blog.pythonanywhere.com/158/ Upon finishing Part 2 the above guide, all codes work fine according to the guides. My first point is to add another user from Python code. The second point is to add a new column to the users table called "email" and add a user from flask_app.py code.

Before the Python code modification, I run the following from bash to add a user to the users table:

export FLASK_APP=flask_app.py

flask shell
>>>from flask_app import db, User
>>>from werkzeug.security import generate_password_hash

>>>someone = User(username="someone", password_hash=generate_password_hash("super"))
>>>db.session.add(someone)
>>>db.session.commit()
Ctrl-D

All went well! Then, I took a further step to alter the flask_app.py with the purpose to apply it into Python code. I tried to modify flask_app.py, main_page.html, and used a modified login form as a register form. The following codes were added to flask_app.py:

from flask_app import db, User #at line 10

An exclamation sign at:
db = SQLAlchemy(app)
#redifinition of unused 'db' from line 10
class User(UserMixin, db.Model):
#redifinition of unused 'User' from line 10

Also, without applying (from flask_app import db, User) at the top, the register form appeared when tapping the register link at main_page form. I try this attempt on main_page.html:

@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        user = load_user(request.form["username"])
        password = load_user(request.form["password"])
        error = None
        if error is None:
            db.execute(
                'INSERT INTO user (user, password) VALUES (username, password)',
                (user, generate_password_hash(password))
            )
            db.session.commit()

    return render_template('register.html')

When I tap at the register button, it redirects to the main page and does nothing to the users table. Any suggestions for adding a user to users table from flask_app.py? When this code works, my next step may be adding an email field to the table and calling it from Python code in a register form. I may try using the migration process.

Kamus

If it's just going to the register page, then the most likely cause of that is that the form that you're using is not submitting a POST request, but a GET request. Check that form that you're submitting and make sure it has POST for its method.

Hi glenn, After checking the register form, it seems that these codes showing a POST method on register.html as in the following:

                <form action="." method="POST">
                <div class="form-group">
                    <label for="username">Username:</label>
                    <input class="form-control" id="username" name="username" placeholder="Enter your username" required>
                </div>
                <div class="form-group">
                    <label for="password">Password:</label>
                    <input type="password" class="form-control" id="password" name="password" placeholder="Enter your password" required>
                </div>
                <button type="submit" class="btn btn-success">Send</button>
            </form>

Thank you for your reply

The perhaps you can try removing the import that is causing the warnings. If you're creating the variables, then you do not need to import them.

Hi glenn, Thank you for your directions. When I remove this line:

from flask_app import db, User

The exclamation mark disappears. Now, to add a user to the table, should I use

Insert into user (user, password) VALUES ...

or

db.session.add command

If you're using db object in your code, you should not delete the whole line, only the User in it.

Hello pafk, Thank you for this urgent reply. It seems that both db and User have interrupted in Python code. If I use only User in import:

from flask_app import User

The following User class unused

class User(UserMixin, db.Model):
# redefinition of unused 'User' from line 10

If the db were used, it turns out to be unused at this line:

from flask_app import db

Then

db = SQLAlchemy(app)
# redefinition of unused 'db' from line 10

If you are defining something in a file, then you'll get that error if you also import it. Perhaps you need to look at your code and rename some things to avoid the name collisions or perhaps you just need to decide whether you want the imported thing or the defined thing in that particular file.

Glenn, how are you today? Thank you so much for taking the time to read this. Now, I renamed the user. And I disabled this line because it is probably unrelated to the register function.

from flask_app import User

My line isn't doing anything to MySql. Perhaps, I should focus on this block of code:

@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        Usernew = load_user(request.form["username"])
        password = load_user(request.form["password"])
        error = None
       
        if error is None:
            db.execute(
                'INSERT INTO users (Usernew, password) VALUES (username, password)',
                (Usernew, generate_password_hash(password))
            )
            db.session.commit()

    return render_template('register.html')

I need help for this block of code if anyone could shade light on the right direction on this procedure. My questions to this block are:

  1. Does the load user function be consistent with insert into table command? If it does not, what method to use in this case?

  2. If it does, does it get user and and password variables from the registered form?

  3. Or what command to get variables from users and password fields when the send button is triggered?

  4. How to insert them to MySql users table?

The questions you're asking look like general ones -- on PythonAnywhere forums we're focused mainly on issues related to our service. If you need general tips on programming, please check out bigger forums, like Stack Overflow. You can also check your web app logs (especially the error log), to see if that view is failing with errors.

Hi pafk, thank you for your further suggestions. I think this question is specific. I change my mind to directly jump into the db query. Instead I build a class named "Addusernew" using SQLALCHEMY model:

class Addnewuser(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128))
    password = db.Column(db.password)

My question is, would this class assign variables username and password for database?

I'm afraid I do not understand your question. What do you mean by "class assign variables for database"?

Hi fjl, What I wish is to create an object, so I can add a user session for users table. This function means that if I call this class, will it provide parameters of username and password that can be used to add a user? I assumed that the users table has these columns. Thanks a lot!

I still do not understand the state you are in. Is it the app from the tutorial? If so, why do you want to create a new table duplicating existing "users" one with something that looks like a broken one?

Hi fjl, No, it isn't from the tutorial. Thank you for your help. All I wish to do is add a user into the users table using the Python application because the whole tutorial doesn't feature adding a user from Python app except using bash console.

Let me paraphrase so we can check if we're on the same page: the thing you want to accomplish now is to be able to add users via the web app (using it in a browser) and not only by doing it in a console, right? If so, please follow the tutorial to the end, since it's shown how to do that later on.

Hi pafk, thank you for your attention. Yes, it is what I wish to accomplish to add users to the MySql database from web applications. I already finished both the tutorial part 1 and 2 to the end. And these tutorials are performing admirably without errors.

Tutorial Part 1 web python https://blog.pythonanywhere.com/121/
Tutorial Part  2 web python. https://blog.pythonanywhere.com/158/

Does it mean that the issue is resolved for you?

Hi pafk, none of these tutorials have a guide to add users to the MySql database from web applications.

You're right -- it's not shown directly in the blog, but there are all elements needed to craft it by yourself. Creating a user would be similar to creating a comment -- if you want to use the code from the tutorial, you could add another vew (e.g. register) which would parse the form (similarily to the login view) and save new user in db when provided credentials are valid.

Hi pafk, thank you for your attention, and I would suggest going back to my first post. I added a new register.html and added a link on main_page.html. Also, I defined 'register' to flask_app.py. These codes aren't doing anything to the users table. My question is if there are any missing codes? The Codes on flask_app.py I crafted as follow:

def register():
    if request.method == "POST":
        Usernew = load_user(request.form["username"])
        password = load_user(request.form["password"])
        error = None
        #flash ('kam')
        if error is None:
            db.execute(
                'INSERT INTO users (Usernew, password) VALUES (username, password)',
                (Usernew, generate_password_hash(password))
            )
            db.session.commit()

    return render_template('register.html')

All right -- so now you need to debug it. You may add logging to the view and check what is the value returned by load_user(request.form["username"]) etc. If that returns something, you can try running the db.execute block with those values in the Python REPL (preceding it by importing needed objects from your app) and check if that works.

Hi pafk, thank you. I don't know about debugging. You said to add this line to the view:

load_user(request.form["username"])

Where should I add this line? To login.html or flask_app.py If to login.html where should it be? Heading or body? If to flask_app.py where to put it? @app.route("/login/", methods=["GET", "POST"]) ?

He did not say to add the line. He said to check the value that it returns in the code where you're already calling it. You can print to stderr and the output will appear in your error log.

Hello glenn, thanks for your comment. Now, I try this code:

@app.route('/register' , methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    user = UserClass(request.form['username'] , request.form['password'])
    db.session.add(user)
    db.session.commit()
    #flash('User successfully registered')
    return redirect(url_for('login'))

It renders the register template, and I register a new username and password. In this situation, you can see that I'm using GET. When I hit the Submit button, it redirects to the main_page.html without a sign of error. When I return to the MySql console to examine this table, it appears to be unaffected (no new user were added). I change to POST, and Run it again. Then, I fill in the username and password. When run, it comes with an error log on this line:

user = UserClass(request.form['username'] , request.form['password'])

My code for UserClass is this:

class UserClass(UserMixin, db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128))
    password_hash = db.Column(db.String(128))
    #email = db.Column(db.String(128))
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    def get_id(self):
        return self.username

What will this line's mistake be? Any suggestions for guidance would be greatly appreciated.

Great, it looks like it's moving forward! What's the error you see in the error log?

Hello pafk, thank you for your reply. The error log is:

2022-03-02 05:43:09,786: File "/home/kamusd/mysite/flask_app.py", line 104, in register 
2022-03-02 05:43:09,786: user = UserClass(request.form['username'] , request.form['password']) 
2022-03-02 05:43:09,786: 
2022-03-02 05:43:09,786: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/werkzeug/datastructures.py", line 377, in __getitem__ 
2022-03-02 05:43:09,786: raise exceptions.BadRequestKeyError(key)

I think this line: user = UserClass(request.form['username'] , request.form['password'])

I think it's not the full error message, but guessing from BadRequestKeyError(key) at the end, I'd say that request that you're passing to the register function does not have the 'username' key in the form.

Hi pafk, thank you for your direction. The Errorlog:

**user = UserClass(request.form['username'] , request.form['password'])**

This event error occurs when I hit the register link from main_page.html, and it redirects from main_page.html to the error log. Keep in mind that the error occurs before the register form appears. This is a 'POST' method.

Maybe log the content of the request object before that.

Fjl, thanķ you for your replý. Could you please make a little bit complete sentence on what do you mean by that?

The error code is on the user = UserClass(request.form['username'] , request.form['password'])

What @fjl meant is to add a print call to the view where you have the notorious line: user = UserClass(request.form['username'] , request.form['password']). You can add something like print(request.form, file=sys.stderr) before that line (you'd probably need to add import sys at the beginning of the file as well). Then reload the web app, go to the view in question (in browser), open the error log for you web app and you should see contents of the form somewhere at the bottom of the error log (you may want to add something more to the print call, so it's easier to find in the log).

Hi pafk, this direction is a good learning point for beginners. Thank you very much. I added a line as you suggested. The new 27 error lines were added at the final to the error log. I am quite unfamiliar with it. Below texts are what the 27 lines of error log comes in:

2022-03-05 04:01:47,577: ImmutableMultiDict([]) 
2022-03-05 04:01:47,578: Error running WSGI application 
2022-03-05 04:01:47,583: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. 
2022-03-05 04:01:47,583: KeyError: 'username' 
2022-03-05 04:01:47,583: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 2091, in __call__ 
2022-03-05 04:01:47,583: return self.wsgi_app(environ, start_response) 
2022-03-05 04:01:47,583: 
2022-03-05 04:01:47,584: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 2076, in wsgi_app 
2022-03-05 04:01:47,584: response = self.handle_exception(e) 
2022-03-05 04:01:47,584: 
2022-03-05 04:01:47,584: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 2073, in wsgi_app 
2022-03-05 04:01:47,584: response = self.full_dispatch_request() 
2022-03-05 04:01:47,584: 
2022-03-05 04:01:47,585: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 1518, in full_dispatch_request 
2022-03-05 04:01:47,585: rv = self.handle_user_exception(e) 
2022-03-05 04:01:47,585: 
2022-03-05 04:01:47,585: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 1516, in full_dispatch_request 
2022-03-05 04:01:47,585: rv = self.dispatch_request() 
2022-03-05 04:01:47,585: 
2022-03-05 04:01:47,586: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 1502, in dispatch_request 
2022-03-05 04:01:47,586: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) 
2022-03-05 04:01:47,586: 
2022-03-05 04:01:47,586: File "/home/kamusd/mysite/flask_app.py", line 105, in register 
2022-03-05 04:01:47,586: user = UserClass(request.form['username'] , request.form['password']) 
2022-03-05 04:01:47,586: 
2022-03-05 04:01:47,586: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/werkzeug/datastructures.py", line 377, in __getitem__ 
2022-03-05 04:01:47,586: raise exceptions.BadRequestKeyError(key)

A bit of comments to these information will be valuable.

An addtional information of the MySql Database structure is like this:

id
username
password_hash

This structure is from part 1 of the tutorial.

In my attempt, I also tried to add request.form['id'] by altering to the error line:

user = UserClass**(request.form['id']** , request.form['username'] , request.form['password'])

With this try, the Error is the KeyError: 'id'. Here are 27 lines of errors from the error log:

2022-03-05 05:21:28,129: ImmutableMultiDict([]) 
2022-03-05 05:21:28,130: Error running WSGI application 2022-03-05 05:21:28,134: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. 
2022-03-05 05:21:28,134: KeyError: 'id' 
2022-03-05 05:21:28,134: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 2091, in __call__ 
2022-03-05 05:21:28,134: return self.wsgi_app(environ, start_response) 
2022-03-05 05:21:28,134: 
2022-03-05 05:21:28,134: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 2076, in wsgi_app 
2022-03-05 05:21:28,134: response = self.handle_exception(e) 
2022-03-05 05:21:28,135: 
2022-03-05 05:21:28,135: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 2073, in wsgi_app 
2022-03-05 05:21:28,135: response = self.full_dispatch_request() 
2022-03-05 05:21:28,135: 
2022-03-05 05:21:28,135: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 1518, in full_dispatch_request 
2022-03-05 05:21:28,135: rv = self.handle_user_exception(e) 2022-03-05 05:21:28,135: 
2022-03-05 05:21:28,136: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 1516, in full_dispatch_request 
2022-03-05 05:21:28,136: rv = self.dispatch_request() 2022-03-05 05:21:28,136: 
2022-03-05 05:21:28,136: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/flask/app.py", line 1502, in dispatch_request 
2022-03-05 05:21:28,136: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) 
2022-03-05 05:21:28,136: 
2022-03-05 05:21:28,136: File "/home/kamusd/mysite/flask_app.py", line 105, in register 
2022-03-05 05:21:28,136: user = UserClass(request.form['id'] , request.form['username'] , request.form['password']) 2022-03-05 05:21:28,136: 
2022-03-05 05:21:28,137: File "/home/kamusd/.virtualenvs/flask-tutorial/lib/python3.6/site-packages/werkzeug/datastructures.py", line 377, in __getitem__ 
2022-03-05 05:21:28,137: raise exceptions.BadRequestKeyError(key)

I think these errors may be helpful for experienced analyzers

OK, so that all of that means is that neither id nor username are being sent in the request that your website is posting to the Flask code. What is the HTML code that you have for the form that is being used for the POST?

Hi giles, thank you so much for your attention. The POST method codes from register.html is as follow:

<div class="container">
    <div class="row">
        <form action="." method="POST">
            <div class="form-group">
                <label for="username">Username:</label>
                <input class="form-control" id="username" name="username" placeholder="Enter your username">
            </div>
            <div class="form-group">
                <label for="password">Password:</label>
                <input type="password" class="form-control" id="password" name="password" placeholder="Enter your password">
            </div>
            <button type="submit" class="btn btn-success">Send</button>
        </form>
    </div>
</div>

Regards, Kamus

OK, that looks like it should be OK. What is the exact code that you currently have in your view function? I just took a look at your site and got an error when I clicked on the "register" link on the front page, which suggests that your view code has changed.

Hi giles, thank you for your reply. The codes for register in view function are listed at the end if this listing.

from datetime import datetime
from flask import Flask, redirect, render_template, request, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_login import login_user, LoginManager, UserMixin, logout_user, login_required, current_user
from werkzeug.security import check_password_hash, generate_password_hash
from flask_migrate import Migrate
#from flask_app import User
import sys

app = Flask(__name__)
app.config["DEBUG"] = True

SQLALCHEMY_DATABASE_URI = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format( username="******", password="********", hostname="*****.mysql.pythonanywhere-services.com", databasename="******$*******",)

app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)
migrate = Migrate(app, db)
app.secret_key = "something only you know"
login_manager = LoginManager()
login_manager.init_app(app)

class UserClass(UserMixin, db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128))
    password_hash = db.Column(db.String(128))
    def check_password(self, password):
        return check_password_hash(self.password_hash, password)
    def get_id(self):
        return self.username

@login_manager.user_loader
def load_user(user_id):
    return UserClass.query.filter_by(username=user_id).first()

class Comment(db.Model):
    __tablename__ = "comments1"
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.String(4096))
    posted = db.Column(db.DateTime, default=datetime.now)
    commenter_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
    commenter = db.relationship('UserClass', foreign_keys=commenter_id)

comments = [] #comment viewing

@app.route("/", methods=["GET", "POST"])
def index(): # index view display comments
    if request.method == "GET":
        return render_template("main_page.html", comments=Comment.query.all())
    if not current_user.is_authenticated:
        return redirect(url_for('index'))
    comment = Comment(content=request.form["contents"], commenter=current_user)
    db.session.add(comment)
    db.session.commit()
    return redirect(url_for('index'))

@app.route("/login/", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login_page.html", error=False)
    userlocal = load_user(request.form["username"])
    if userlocal is None:
        return render_template("login_page.html", error=True)
    if not userlocal.check_password(request.form["password"]):
        return render_template("login_page.html", error=True)
    login_user(userlocal)
    return redirect(url_for('index'))

@app.route("/logout/")
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route("/forgot/")
def forgot():
    return render_template("forgot.html")

@app.route('/register' , methods=['GET','POST'])
def register():
    if request.method == 'POST':
        return render_template('register.html')
    print(request.form, file=sys.stderr) #useful debug
    user = UserClass(request.form['username'] , request.form['password'])
    db.session.add(user)
    db.session.commit()
    return redirect(url_for('login_page.html'))

Best regards, Kamus

When someone tries to go to /register endpoint they are making a GET request, but in your code it goes to line when it tries to access content of a form that is available only in POST request.

Fjl, thanks for your comment. I am quite lost from your direction. Did you mean to use 'GET' for request method? Using 'GET' in the request method will display the register form, but it will not add records into the users table. For example, it will not insert a new users, when I fill in the register form and hit submit. Instead, it will redirect to main page.

I guess what @fjl meant is that your code is written in such a way that whenever someone's visiting the register view, the code which is being executed expects that the request will have a form, but it doesn't. And conversely -- if a user sends a POST request (probably with a form), the only thing your code is doing is rendering the register.html template. I think you have a wrong control flow here.

@app.route('/register' , methods=['GET','POST'])
def register():
    # this block will be executed when POST sent
    if request.method == 'POST':
        return render_template('register.html')

    # this block will be executed when GET sent
    print(request.form, file=sys.stderr) #useful debug
    user = UserClass(request.form['username'] ,
    request.form['password'])
    db.session.add(user)
    db.session.commit()
    return redirect(url_for('login_page.html'))

Hello pafk, thank you for your thought. I try like this:

@app.route('/register' , methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('register.html')
    if request.method == 'POST':
        print(request.form, file=sys.stderr) #useful debug
        user = UserClass(request.form['username'] , request.form['password'])
        db.session.add(user)
        db.session.commit()

Although this code run without error, it does not achieve its purpose. A notion of this code is for adding users to the users table. The line does not doing anything to the database when press submit:

user = UserClass(request.form['username'] , request.form['password'])

I believe we already provided you with all the debugging tips needed -- if the code is not working you can 1) check your web app's error log and see if, where and how the code is failing, 2) add more logging (e.g. check if user is created properly; also, the line you quoted is not doing anything to the database, it is intended to create an instance of the UserClass, the lines following, where you do something with the db object are intended to change the state of the database). Our forums are dedicated to PythonAnywhere related issues -- you are asking general programming questions. There are lots of forums dedicated to programming issues (like Stack Overflow) and online tutorials for Python, Flask and MySQL.

pafk and all people who commented, thank you for your supports to this issue. I will get more insight from more sources to get this project running. I am curious on ImmutableMultidic[] cases. With this line, immutablemultidic is solved, but another keyerror arise:

UserClass = request.form.to_dict()

I don't see any way that that like could cause a keyerror. Are you sure it's that line? Are you sure it's a keyerror?

@glenn, my posting about error log above have ImmutableMultiDict([]) did you see it? Then, I use UserClass = request.form.to_dict(), and I debug using print(request.form, file=sys.stderr). Then immutablemultidic is no more appear at errorlog.

What was the full error message related to the ImmutableMultiDict in the error log?

Hi pafk, the key points are:

2022-03-05 04:01:47,577: ImmutableMultiDict([]) 
2022-03-05 04:01:47,578: Error running WSGI application 
2022-03-05 04:01:47,583: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. 
2022-03-05 04:01:47,583: KeyError: 'username'

And:

2022-03-05 04:01:47,586: File "/home/kamusd/mysite/flask_app.py", line 105, in register 
2022-03-05 04:01:47,586: user = UserClass(request.form['username'] , request.form['password'])

And how your current code for that view look like?

2022-03-05 04:01:47,577: ImmutableMultiDict([]) -- that doesn't look like an error message, it's rather effect of printing something (did you try to print the request.form object?), and it shows that it was empty. That probably caused the error that is shown later -- KeyError -- which probably means that you didn't provide the value for username in the request (the second block shows the code that caused this error, I guess).

@pafk, thank you for your reply. It shows nothing when I use print(request.form). But it returns "{}" when I use return(request.form).

What I didn't know is whether or not it is possible to use both "GET" and "POST" for a register form? Like this one:

@app.route('/register' , methods=['GET','POST'])

def register():
    if request.method == 'GET':
        return render_template('register.html')
        if request.method == 'POST':
            user = UserClass(username="admin2", password_hash=generate_password_hash("secret"))
            db.session.add(user) #5
            db.session.commit()
            return (request.form)# {}

if request.method == 'POST' is nested under if request.method == 'GET It's unreachable code. Both conditions could not be true at the same time.

@fjl, thank you for your response. How about this:

def register():
    if request.method == 'GET':
        return render_template('register.html')
    if request.method == 'POST':
        user = UserClass(
            username=request.form["username"],
            password_hash=request.form["password"],
        )
        db.session.add(user) #5
        db.session.commit()
    return (request.form)# {}

Now you have two separate blocks for GET and POST -- I'm not sure if return (request.form) is exactly what you want though. And -- if you're keeping your code explicit, I guess the return statement at the end should be indented.

Hi pafk, thanks you for your continous supports. I re-assembled these codes into another account, and I got the expected result from return (request.form). The out put displayed in return(request.form) for what I typed into the register.html when I hit "submit". However, there is an errorlog when I commented the return (request.form). The keyerror addressed in the "contents" block of 'index' view in flask_app.py, instead of in the register view. I didn't know why errorlog pointed keyerror: "contents" to line 41 "dbs.sesion.add(comment)"

flask_app.py code:

class Comment(dbs.Model):
    __tablename__ = "comments1"
    id = dbs.Column(dbs.Integer, primary_key=True)
    content = dbs.Column(dbs.String(4096))

class User(dbs.Model):
    __tablename__ = "users"
    id = dbs.Column(dbs.Integer, primary_key=True)
    username = dbs.Column(dbs.String(128))
    password_hash = dbs.Column(dbs.String(128))

comments = [] 
username = []

@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "GET":
        #return render_template("main_page.html", comments=comments) #data is not save to mysql
        return render_template("main_page.html", comments=Comment.query.all())#data is queried to mysql
    #return (request.form)
    comment = Comment(content=request.form["contents"])
    dbs.session.add(comment)
    dbs.session.commit()
    return redirect(url_for('index'))

@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method =="GET":
        #return render_template("register.html", username=username)
        return render_template("register.html", username=User.query.all())
    #return (request.form)#ok return something
    username1 = User(username=request.form["username"])
    dbs.session.add(username1) #5
    dbs.session.commit()
    return redirect(url_for("register.html"))

main_page.html code:

<html>
    <head>
        <title>My scratchboard page</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

</head>
<body>

    <nav class="navbar navbar-inverse">
        <div class="container">

            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button> <a class="navbar-brand" href="#">My scratchpad</a>
            </div>
        </div>
    </nav>
    <div class="container">

        {% for comment in comments %}
            <div class="row">
                {{ comment.content }}
            </div>
        {% endfor %}

        <div class="row">
            <form action="." method="POST">
                <textarea class="form-control" name="contents" placeholder="Enter a comment"></textarea>
                <input type="submit" class="btn btn-success" value="Post comment">
            </form>
        </div>

        <ul class="nav navbar-nav navbar-right">
            <li><a href="{{ url_for('register') }}">Register</a></li>
        </ul>

    </div><!-- /.container -->
</body>
</html>

register.html code:

<html>
    <head>
        <title>My scratchboard page</title>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">

</head>
<body>

    <nav class="navbar navbar-inverse">
        <div class="container">

            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button> <a class="navbar-brand" href="#">My scratchpad</a>
            </div>
        </div>
    </nav>
    <div class="container">
        {% for username1 in username %}
            <div class="row">
                {{ username1.username }}
            </div>
        {% endfor %}

        <div class="row">
            <form action="." method="POST">
                <textarea class="form-control" name="username" placeholder="Enter a user"></textarea>
                <input type="submit" class="btn btn-success" value="Post user">
            </form>
        </div>


    </div><!-- /.container -->
</body>
</html>

errorlog:

2022-03-21 06:36:08,101: Error running WSGI application 
2022-03-21 06:36:08,102: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. 
2022-03-21 06:36:08,103: KeyError: 'contents' 
2022-03-21 06:36:08,103: File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2069, in __call__ 
2022-03-21 06:36:08,103: return self.wsgi_app(environ, start_response) 
2022-03-21 06:36:08,103: 
2022-03-21 06:36:08,103: File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2054, in wsgi_app 
2022-03-21 06:36:08,103: response = self.handle_exception(e) 
2022-03-21 06:36:08,104: 
2022-03-21 06:36:08,104: File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2051, in wsgi_app 
2022-03-21 06:36:08,104: response = self.full_dispatch_request() 
2022-03-21 06:36:08,104: 
2022-03-21 06:36:08,104: File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1501, in full_dispatch_request 
2022-03-21 06:36:08,104: rv = self.handle_user_exception(e) 
2022-03-21 06:36:08,104: 
2022-03-21 06:36:08,105: File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1499, in full_dispatch_request 
2022-03-21 06:36:08,105: rv = self.dispatch_request() 
2022-03-21 06:36:08,105: 
2022-03-21 06:36:08,105: File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1485, in dispatch_request 2022-03-21 06:36:08,105: return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) 
2022-03-21 06:36:08,105: 
2022-03-21 06:36:08,106: File "/home/kamusg/mysite/flask_app.py", line 41, in index 
2022-03-21 06:36:08,106: dbs.session.add(comment) 
2022-03-21 06:36:08,106: 
2022-03-21 06:36:08,106: File "/usr/local/lib/python3.6/site-packages/werkzeug/datastructures.py", line 377, in __getitem__ 
2022-03-21 06:36:08,106: raise exceptions.BadRequestKeyError(key)

As pafk mentioned already we do not provide debugging service. Again you need to inspect what your web app is producing, check requests you are sending and check what happens with data that is posted (if it's posted), etc.

Hi fjl, It returns this from request.form:

{ 
"password": "12355", 
"username": "Kkkkk" 
}

So it looks like there are no contents in the request, as the error message suggests.