从变量sqlite python3 sqlalchemy获取列名

时间:2019-05-18 07:27:48

标签: python python-3.x sqlite flask flask-sqlalchemy

我想使用flask sqlalchemy将存储在x变量中的详细信息存储到sqlite数据库。如何使其成为可能。

这是我写的代码:

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)

在sqlite中创建的表:

id   u1  p1

需要在sqlite中创建表并加载数据:

id username password
1  sam      sam123

1 个答案:

答案 0 :(得分:2)

您的表需要用所需的名称定义列:

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))

您可以使函数从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

并创建一个User实例,如下所示:

username, password = get_user_data(x)
user = User(username=username, password=password)