get column names from variables sqlite python3 sqlalchemy - python

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

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)

Related

Pandas to_sql() table not allowing me to insert new rows

I have code that converts a csv into an sqlalchemy table. When I try and use db.session.add() it creates an entry in the datatable, but the id is null. This stops me from being able to interact with the data. I tried creating a normal SQL alchemy table and was able to insert rows fine, but for whatever reason the way pandas added the table is preventing me from adding more rows to the table. I will attach the relevant code. Let me know if you need more
db = SQLAlchemy()
DB_NAME = "database.db"
app = Flask(__name__)
sslify = SSLify(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db.init_app(app)
class Master(db.Model):
__tablename__ = "Master"
__table_args__ = {'extend_existing':True}
index = db.Column(db.Integer, primary_key = True)
username = db.Column(db.String(150))
full_name = db.Column(db.String(150))
serial_number = db.Column(db.String(150))
asset_tag = db.Column(db.Integer)
def __repr__(self):
return '<Comments %r>' % self.id
def __init__(self, username, full_name, serial_number, asset_tag):
self.username = username
self.full_name = full_name
self.serial_number = serial_number
self.asset_tag = asset_tag
file_name = 'master.csv'
df = pd.read_csv(file_name)
df['asset_tag'].fillna('-999', inplace=True)
df['asset_tag'] = df['asset_tag'].astype('int')
df.replace(-999," ",inplace=True)
df.fillna(" ", inplace=True)
df.to_sql(con = app.config['SQLALCHEMY_DATABASE_URI'], index_label='index', name=Master.__tablename__, if_exists='append')
#app.route('/adds', methods = ['GET','POST'])
def adds():
thefullname = request.form.get('add_full')
theuser = request.form.get('add_user')
theasset = request.form.get('add_asset')
theserial = request.form.get('add_serial')
theadd = Master(username = theuser, full_name=thefullname, asset_tag=theasset, serial_number=theserial)
db.session.add(theadd)
db.session.commit()
return render_template('home.html')

SQLAlchemy many-many assoc table not populating

I'm trying to make a pair of tables with a many-many relationship. Here's my code to set up the tables:
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
recipe_ingredient = db.Table('recipe_ingredient',
db.Column('recipe_name', db.String(64), db.ForeignKey('recipe.name')),
db.Column('ingredient_name', db.String(64), db.ForeignKey('ingredient.name'))
)
class Recipe(db.Model):
name = db.Column(db.String(64), primary_key = True)
ingredients_for = db.relationship('Ingredient', secondary='recipe_ingredient', backref='recipes_for')
def __repr__(self):
return f'<Recipe: {self.name}>'
class Ingredient(db.Model):
name = db.Column(db.String(64), primary_key = True)
def __repr__(self):
return f'<Ingredient: {self.name}>'
Now, here's some test code to try and add data to the tables:
db.create_all()
r0 = Recipe(name='eggsandwich')
db.session.merge(r0)
r1 = Recipe(name='tomatoegg')
db.session.merge(r1)
i0 = Ingredient(name='egg')
db.session.merge(i0)
i1 = Ingredient(name='bread')
db.session.merge(i1)
i2 = Ingredient(name='tomato')
db.session.merge(i2)
db.session.commit()
r0.ingredients_for.append(i0)
r0.ingredients_for.append(i1)
r1.ingredients_for.append(i0)
r1.ingredients_for.append(i2)
db.session.commit()
print([i.name for i in i.ingredients_for])
When I run this, it prints "['eggsandwich', 'tomatoegg']", as expected. However, in DB Browser, the recipe_ingredient table is empty:
Why isn't this table populating? How do I get the relationships to show up there?

How to query with many tables

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
#import sqlite3 as sql
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://ahmad:ahmad#192.168.3.103/utama'
db = SQLAlchemy(app)
class ak(db.Model):
__tablename__ = 'ak'
id = db.Column(db.Integer, primary_key=True)
nama = db.Column(db.String)
alamat = db.Column(db.String)
akreditasi = db.Column(db.String)
def __init__(self, id, nama, alamat, akreditasi):
self.id = id
self.city = nama
self.alamat = alamat
self.akreditasi = akreditasi
class av(db.Model):
__tablename__ = 'av'
id = db.Column(db.Integer, primary_key=True)
nama = db.Column(db.String)
alamat = db.Column(db.String)
akreditasi = db.Column(db.String)
def __init__(self, id, nama, alamat, akreditasi):
self.id = id
self.city = nama
self.alamat = alamat
self.akreditasi = akreditasi
id_jurusan = db.Table('id_jurusan',
db.Column('id', db.Integer, db.ForeignKey('ak.id')),
db.Column('id', db.Integer, db.ForeignKey('av.id'))
)
#app.route('/ak')
def jurusan(jurusan):
return render_template('index.html', rows=ak.query.all() )
#app.route('/av')
def Akuntansi():
return render_template('index.html', rows=av.query.all() )
if __name__ == '__main__':
app.run(debug=True, host='1.1.1.1', port=80)
I am a new to learn python, in this case I studied the framework flask and I had trouble on the declaration SQLAlchemy, precisely displays the contents of the table but with the same structure,when executed will be like this.....
[
which one success
You are using the decorator
#app.route('/av')
The method which succeeds Akuntansi() does not require a parameter. So this works. The method which fails expects a parameter jurusan(jurusan) but your decorator #app.route('/ak') does not consider this.
To pass a parameter you need to use the decorator like this:
#app.route("/ak/<jurusan>") and then also pass the parameter in the request.

How to query multiple items using Flask SQLAlchemy

After importing the modules:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
and declaring app and db objects:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)
I go ahead and create two tables: User and Email:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
addresses = db.relationship('Email', backref='person', lazy='dynamic')
class Email(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
person_id = db.Column(db.Integer, db.ForeignKey('user.id'))
With db.relationship in place I can now link some multiple emails to the same user. First I create two email addresses:
first_email = Email(email='first#email.com')
second_email = Email(email='second#email.com')
Then I am passing these two emails to User class at the time it is being created:
user = User(name='User Name', addresses = [first_email, second_email])
To see which user is linked to which email I can simply use:
print first_email.person
print user.addresses.all()
Now I want to add another third email to the same user. How do I append a new email to the list of the emails that have been already linked to the user?
new_email = Email(email='new_email#example.com')
user.addresses.append(new_email)
db.session.commit()
This will append the email address to the relationship.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///inquestion.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
addresses = db.relationship('Email', backref='person', lazy='dynamic')
def add_email(self, new_email):
linked_emails = [email.email for email in self.addresses.all()]
if not new_email in linked_emails:
linked_emails.append(new_email)
self.addresses = [Email.find_or_create(email) for email in linked_emails]
class Email(db.Model):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(50))
person_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#staticmethod
def find_or_create(email):
try:
return Email.query.filter_by(email=email).one()
except:
new_email = Email(email=email)
db.session.add(new_email)
db.session.commit()
return new_email
first_email = Email(email='first#email.com')
second_email = Email(email='second#email.com')
user = User(name='User Name', addresses = [first_email, second_email])
db.drop_all()
db.create_all()
db.session.add(first_email)
db.session.add(second_email)
db.session.add(user)
db.session.commit()
# some extra queries
user.add_email('third#email.com')
print user.addresses.all()
print Email.find_or_create('fourth#email.com')
print Email.query.filter_by(email='fourth#email.com').one().email
print first_email.query.filter_by(email='second#email.com').one()

Select query fails in sqlalchemy

Please i am having this issue with my first sqlachemy app. I am trying to query the db which is posgres and return a row where it matches . Below is my code.
app.py
from sqlalchemy.orm import sessionmaker
from models.models import Base,User,Product,ProductItem,DATABASE, initialize
engine = DATABASE
Base.metadata.bind = (engine)
DBSession = sessionmaker(bind=engine)
session = DBSession()
....
#app.route('/login', methods = ['GET','POST'])
def login():
form = RegisterForm.LoginForm()
if request.method == 'GET':
return render_template('login.html', form=form)
return authenticate(form = form)
def authenticate(form):
if form.validate_on_submit():
try:
user = session.query(User).filter(User.email == 'xxxx#yahoo.com')
if session.query(exists().where(User.email == form.email.data)).scalar() :
return user.name
except :# models.DoesNotExist:
flash("Your email or password does not match !", "error")
return 'error'
my modules is in a seperate folder modules
modules/modules.py
#declarations
Base = declarative_base()
engine = create_engine('postgresql://postgres:0102443167#localhost:5432/postgres',echo=True)
Base.metadata.bind = (engine)
DBSession = sessionmaker(bind=engine)
session = DBSession()
DATABASE = engine
class User(UserMixin , Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
title = Column(CHAR(3), nullable = False)
fname = Column(String(100), nullable = False)
lname = Column(String(100), nullable = False)
username = Column(String(100), nullable = False, unique = True)
email = Column (String(50), nullable =False, unique = True)
password = Column(String(100), nullable = False)
address = Column(String(250), nullable = False)
state = Column(String(50), nullable = False)
is_Admin = Column(Boolean ,default = False)
is_Logged = Column(Boolean, default = False)
is_Active = Column (Boolean , default = False)
is_Block = Column(Boolean, default = False)
joined_On = Column(ArrowType)
......
My problem is with the app.py authenticate method. The code
user = session.query(User).filter(User.email == form.email.data)
Raise an error. When i check form.email.data return correct string. However when i tried
if session.query(exists().where(User.email == form.email.data)).scalar() :
return 'Ok'
works as expected. It works perfect and thus make me realize the issue might be with my query . I then tried
if session.query(exists().where(User.email == form.email.data)).scalar() :
return user.lname
and it raise error saying user does not have property name which should have. I am confuse. Please how do i query record from my tables ? Any help would be appreciated
You have to get the first object which matches the query so you have to add .first() at the end of the query:
user = session.query(User).filter(User.email == form.email.data).first()
See here more info.

Categories