Python Forum
Python keeps inserting NULL values into table
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python keeps inserting NULL values into table
#1
Hey guys I'm not getting any errors but my username and password are always added to the table as NULL. Anyone know why?

Thanks!

Python: https://pastebin.com/efvtFYDK
HTML: https://pastebin.com/b3HzpEsv
Terminal: https://www.picpasteplus.com/v.php?i=aed4900e61
Reply
#2
Please post code in code tags and not use links, Thank you
I lot of folks will skip if they have to follow a link
Reply
#3
import os
import psycopg2

from flask import Flask, session, render_template, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker


app = Flask(__name__)

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))


@app.route("/")
def index():
    return "Project 1: TODO"



try:
    connection = psycopg2.connect(user = "zpztmsdffwqvs",
                                  password = "16671705ed2adsfd7855f36cb8c05a5188abc7fd823c850e46625",
                                  host = "ec2-54-33-37-321.compute-1.amazonaws.com",
                                  port = "5432",
                                  database = "dafdafsdasd")

    cursor = connection.cursor()
    

except (Exception, psycopg2.Error) as error :
    print ("Error while connecting to PostgreSQL", error)
finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
            
            
          
@app.route("/register", methods=["GET", "POST"])
def register():
    
    if request.method == "GET":
        return render_template("register.html")
    elif request.method == "POST":
        password = request.form.get("password")
        username = request.form.get("username")
        print (username)
        print (password)
        # session.clear()
        # db.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username":username, "password":password})
        # db.commit()
        return render_template("register.html", message=username)

            
            

should i start a new thread?
Reply
#4
I'm not sure why it's putting NULL for username and NULL for password instead of the user input. Can someone please help me?

Thanks.

import os
import psycopg2

from flask import Flask, session, render_template, request
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker


app = Flask(__name__)

# Check for environment variable
if not os.getenv("DATABASE_URL"):
    raise RuntimeError("DATABASE_URL is not set")

DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Set up database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))


@app.route("/")
def index():
    return "Project 1: TODO"



try:
    connection = psycopg2.connect(user = "zpztmsgfdceigfwqvs",
                                  password = "fsgfdfg",
                                  host = "ec2-54-55-37-115.compute-1.amazonaws.com",
                                  port = "5432",
                                  database = "sdgfd")

    cursor = connection.cursor()
    

except (Exception, psycopg2.Error) as error :
    print ("Error while connecting to PostgreSQL", error)
finally:
    #closing database connection.
        if(connection):
            cursor.close()
            connection.close()
            print("PostgreSQL connection is closed")
            
            
          
@app.route("/register", methods=["GET", "POST"])
def register():
    
    if request.method == "GET":
        return render_template("register.html")
    elif request.method == "POST":
        password = request.form.get("password")
        username = request.form.get("username")
        session.clear()
        db.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username":username, "password":password})
        db.commit()
        return render_template("register.html", message=username)

            
            
Reply
#5
Are you sure you're using the correct syntax for the placeholders in the statement? The docs suggest that what you're doing is incorrect.

Also, a couple of things:

1
You shouldn't leave your DB connection details in your post.

2. Is this application for your own learning or something meant for serious use? If the latter, you shouldn't be storing passwords in the clear; they should be hashed and salted.
Reply
#6
it's just for learning and i changed the database info don't worry.

Also - I think this is OK for placeholders I am getting no syntax errors.
Reply
#7
(Jun-09-2020, 02:27 AM)card51shor Wrote: should i start a new thread?
Generally you shouldn't have started these 2 threads that I merged. There is your original one where we were iterating over the syntax of the SQL statement. This time I will not merge this into the original one, because the original one was bloated not without my fault.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#8
OK thank you. My issue now is that it is putting fields into username and password but they are both NULL. Any idea why? Thanks
Reply
#9
I don't know why you'd use different placeholders than the docs suggest and assume it works. I can't explain why no exception is thrown and don't have time to dig into the source, but I'd at least try using the placeholders mentioned in the docs to rule that possibility out (or in).
Reply
#10
db.execute("INSERT INTO users (username, password) VALUES (:username, :password)", {"username":username, "password":password})

What should this be then? I can't figure it out with the documentation u sent. Before it used to give me a syntax error before i corrected it now I'm not getting an error but the values are NULL still.


Tried this:

db.execute("INSERT INTO users (username, password) VALUES (%s, %s)", ("username", "password",))

Now I get an error when I click the register button:

AttributeError: 'tuple' object has no attribute 'keys'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Problem with number of rows containing null values PythonSpeaker 3 2,251 Nov-23-2019, 06:53 PM
Last Post: ibreeden
  Issues with Inserting Values into an Empty List with a While Loop TommyMer 2 3,779 Sep-12-2018, 12:43 AM
Last Post: TommyMer
  file a table of values Ybivashka322 4 3,719 Dec-14-2017, 06:11 PM
Last Post: mpd

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020