-2

i have a sqlite database which looks like below:

id  user_id  name   data

i want to save the data to the sqlite database. i will get name and data from the user. Here i have written the code to save data. but the issue is, if the user enters the same data, it saves it. i don't want that same data to be saved again. I used if else condition but it checks only first row. How to make it check multiple rows. How to make it possible

Here's the Code:

from flask import Flask, request, jsonify, abort, url_for
from flask_httpauth import HTTPBasicAuth
from flask_sqlalchemy import SQLAlchemy
from passlib.apps import custom_app_context as pwd_context
import datetime

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/data_logs2.db'
db = SQLAlchemy(app)
auth = HTTPBasicAuth()
idd = 1

class PersonData(db.Model) :
    __tablename__ = 'person_data'
    id = db.Column(db.Integer, primary_key = True)
    user_id = db.Column(
                        db.Integer,
                        nullable=False
                        )
    name = db.Column(db.String(128))
    data = db.Column(db.String(128))
@app.route('/savedata',methods=['POST'])
def save_data():
    name = request.form['name']
    datas = request.form['data'] 
    print()
    personData = PersonData.query.filter_by(user_id=idd).first()
    if personData:
        if personData.data != datas:
            personData = PersonData(user_id = idd, name = name, data =datas)
            db.session.add(personData)
            db.session.commit()
        elif personData.name != name:
            personData = PersonData(user_id = idd, name = name, data =datas)
            db.session.add(personData)
            db.session.commit()
        else:    
            personData.data = datas
            db.session.commit()
    else:
        personData = PersonData(user_id = idd, name = name, data =datas)
        db.session.add(personData)
        db.session.commit()
    return jsonify({'success':'true'}) 

if __name__ == '__main__':
    db.create_all()
    app.run(host='0.0.0.0', port=5001)

Data stored in table:

id  user_id name    data
1   1       steve1  sample data1
2   1       steve2  sample data2
3   1       steve3  sample data3
4   1       steve3  sample data3
5   1       steve2  sample data2
6   1       steve5  sample data5

Required Output to be stored in table:

id  user_id name    data
1   1       steve1  sample data1
2   1       steve2  sample data2
3   1       steve3  sample data3
4   1       steve5  sample data5
davidism
  • 121,510
  • 29
  • 395
  • 339
Smack Alpha
  • 1,828
  • 1
  • 17
  • 37

1 Answers1

2

In smaller dataset you can easily solve it by getting all rows:
personData = PersonData.query.filter_by(user_id=idd).all()
and testing against it:

for row in personData:
    if (...)

You can also try to select data matching your new data (using and_):

from sqlalchemy import and_ 
personData = PersonData.query.filter(and_(user_id=idd, name=name, data=datas).first()
if personData:
    print("You already have this data in db!")

If you have many rows, however, it could get slow and should be preferably managed on a database level, using constraints. This is explained here:

ALTER TABLE votes ADD UNIQUE unique_index(user, email, address);


I don't fully understand your use-case, but it seems to me there should be a better way to structure your data.
For example, what is the meaning of the name column?


Also, not really in relation to your question, but I would recommend naming your variables according to PEP8 convention, so naming your variable person_data is preferable to personData.

janpeterka
  • 568
  • 4
  • 17