Home > Software design >  How not to send null data to a database created with SQLalchemy in flask application?
How not to send null data to a database created with SQLalchemy in flask application?

Time:09-06

I am creating my first database in Flask application, to create this database I used SQLalchemy.

I manage to create the table, however for one reason when I submit the form it is sending null data, I believe it is at the time push the data to the table.

But as I have no experience with database, I know it is an easy problem, but I am having a certain difficult with it.

  • Python code
def template():

    if request.method == "POST":

        company_name = request.form["company"]
        address_name = request.form["address"]    
        host_name = request.form["host"]
        port_name = request.form["port"]
        user_name = request.form["user"]
        password_name = request.form["password"]

        company_new = Camera(company=company_name)
        address_new = Camera(address=address_name)    
        host_new = Camera(host=host_name)
        port_new = Camera(port=port_name)
        user_new = Camera(user=user_name)
        password_new = Camera(password = password_name)
        
        try:
            db.session.add(company_new)
            db.session.add(address_new)
            db.session.add(host_new)
            db.session.add(port_new)
            db.session.add(user_new)
            db.session.add(password_new)
            db.session.commit()
            return redirect('/template')

        except OSError as e:
            print("Error: %s" % (e.strerror))
  • HTML code

  <div >
    <label  for="company">Empresa:</label>
    <div >
      <input  name="company" id="company" required>
    </div>
  </div>
  <div >
    <label  for="address">Endereço:</label>
    <div >
      <input  name="address" id="address" required>
    </div>
  </div>
     
   .
   .
   .

    <div >
      <button  id="submit" type="submit" ><i ></i> Conectar</button><br>
    </div>
</form> 
  • Database result
id  company address port    host    user    password    date
1   dwds    null    null    null    null    null    2022-09-05 20:22:48.940506
2   null    sds     null    null    null    null    2022-09-05 20:22:48.944498
3   null    null    sd      null    null    null    2022-09-05 20:22:48.945148
4   null    null    null    s       null    null    2022-09-05 20:22:48.945148
5   null    null    null    null    s       null    2022-09-05 20:22:48.945148
6   null    null    null    null    null    s       2022-09-05 20:22:48.945827

CodePudding user response:

You need to union all your Camera objects into one

camera_object = Camera(
    company=company_name, 
    address=address_name, 
    host=host_name, 
    port=port_name, 
    user=user_name, 
    password = password_name
)
db.session.add(camera_object)
db.session.commit()

and do not store passwords without hashing :)

  • Related