Andishe
Andishe

Reputation: 115

sqlalchemy insert data does not work

In models.py I have define:

class slidephoto(db.Model):
    __tablename__ = 'slide_photo'
    id = db.Column(db.Integer, primary_key=True)
    uid = db.Column(db.Integer, nullable=False)
    photo = db.Column(db.String(collation='utf8_bin'), nullable=False)

    def __init__(self, uid, photo):
        self.uid = uid
        self.photo = photo

    def __repr__(self):
        return "{'photo': " + str(self.photo) + "}"

I select data like this (for example):

@app.route('/index/')
def index():
    user_photo = slidephoto.query.filter_by(uid=5).all()

Now I want to know how to insert data. I tried this:

@app.route('/insert/')
def insert():
    act = slidephoto.query.insert().execute(uid='2016', photo='niloofar.jpg')
    return 'done'

But it does not do what I need. What should I do?

I have read and tested other answers and solutions, but none of them was useful for my script.

================ update ================

I don't no if it helps... but here is all imports and configs in app.py:

import os, sys
from niloofar import *
from flask import Flask, request, url_for, render_template, make_response, redirect
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://myusername:mypassword@localhost/mydbname'
db = SQLAlchemy(app)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

Upvotes: 5

Views: 11953

Answers (3)

Jalal
Jalal

Reputation: 417

I hope that my answer will help you solving the problem.

from sqlalchemy import create_engine, MetaData, Table, insert
# I have tested this using my local postgres db.
engine = create_engine('postgresql://localhost/db', convert_unicode=True)
metadata = MetaData(bind=engine)
con = engine.connect()
act = insert(slidephoto).values(uid='2016', photo='niloofer.jpg')
con.execute(act)

Upvotes: 2

vlado
vlado

Reputation: 9

You should use query as a method. Like 'query()'

Upvotes: -1

sting_roc
sting_roc

Reputation: 253

I write a simple demo that do insert work, you can take it as a reference:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


class FirstTest(db.Model):
    __tablename__ = "first_test"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)

    def __init__(self, name):
        self.name = name


# Fill your db info here
mysql_info = {
    "user": "",
    "pwd": "",
    "host": "",
    "port": 3306,
    "db": "",
}

app = Flask(__name__)

app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
# Here I use pymysql
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://{0}:{1}@{2}:{3}/{4}".format(
    mysql_info["user"], mysql_info["pwd"], mysql_info["host"],
    mysql_info["port"], mysql_info["db"])

db.__init__(app)


@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    with app.test_request_context("/"):
        record = FirstTest("test")
        db.session.add(record)
        db.session.commit()

Upvotes: 0

Related Questions