How can I add a value to a database from sqlalchemy python?

0

Good afternoon friends of stackoverflow I have a question.

My doubt is that I want to enter a value to a field already registered in a database by means of sqlalchemy python using flask as a microframework here is my code example.

@app.route("/activate_email/<string:email>/<string:username>/<string:hashed_password>")
def activate_email(email, username, hashed_password):
    token = User(token=1)
    db.session.add
    db.session.commit()
    return render_template("activate_email.html", name = username, email=email)

I would like to enter a value of 1 to the token where the email or registered user is. I hope it was very clear otherwise do not hesitate to ask me.

    
asked by Tysaic 27.11.2017 в 20:10
source

1 answer

0

What you have to do is filter the data with the help of filter_by that can be concatenated as shown below, this returns an iterable since there can be several objects that meet the condition, then we update the field that is desired, and we make a commit.

Example:

from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base


Base = declarative_base()

#  id, username, email, password, token.
class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    username = Column(String)
    email = Column(String)
    password = Column(String)
    token = Column(Integer)

from sqlalchemy import create_engine
engine = create_engine('sqlite:///orm_in_detail.sqlite')

from sqlalchemy.orm import sessionmaker
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)

s = session()
user = User(username="username", email="[email protected]", password="password", token=0)
s.add(user)
s.commit()
# filtro 
results = s.query(User).filter_by(username="username").filter_by(email="[email protected]")
for result in results:
    # actualizamos el campo
    result.token = 1
    s.commit()
    
answered by 27.11.2017 / 21:02
source