Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 869
Andishe Avatar asked Nov 08 '22 10:11

Andishe


1 Answers

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)
like image 162
Jalal Avatar answered Nov 14 '22 22:11

Jalal