0

I want to store the details stored in x variable to the sqlite database using flask sqlalchemy. How to make it possible.

Here's the code i wrote:

from flask import Flask
from flask_httpauth import HTTPBasicAuth
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/u.db'
db = SQLAlchemy(app)

class User(db.Model) :
    x = ['username = "sam"', 'password = "sam123"']
    u1 = (x[0].split()[0])
    p1 = (x[1].split()[0])
    print(u1,p1)
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key = True)
    u1 = db.Column(db.String(32), index = True)
    p1 = db.Column(db.String(128))

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

table created in sqlite:

id   u1  p1

Required table to be created in sqlite and data to be loaded:

id username password
1  sam      sam123

1 Answer 1

2

Your table needs to define the columns with the names that you want:

class User(db.Model) :

    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key = True)
    username = db.Column(db.String(32), index = True)
    password = db.Column(db.String(128))

You can make function to extract the username and password from x:

def get_user_data(data):
    user_data = []
    for item in data:
        part = item.partition(' = ')[2]
        cleaned = part.replace('"', '')
        user_data.append(cleaned)
    return user_data

And create a User instance like this:

username, password = get_user_data(x)
user = User(username=username, password=password)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.