Ritesh Jung Thapa Ritesh Jung Thapa - 4 months ago 9
SQL Question

Part of Data get lost on adding to session and commiting flask

The model is

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
artistname = db.Column(db.String(64))
photourl = db.Column(db.String(1000))
contactInfo = db.Column(db.String(20))
description = db.Column(db.String(500))
date = db.Column(db.Date)
def __repr__(self):
return '<User %r>' % (self.photourl)


Here photourl is the url of photos posted.

After form submission.

user = User(artistname = form.artist.data,photourl = "",
description = form.description.data,contactInfo = form.contactinfo.data,date = datetime.datetime.utcnow().date() )


I add all the details without photourl.

Now i make list of all the filenames which is stored in filename variable in below code.And join with * in middle.

filename = "*".join(filename)
print(filename)


The sample output appeared in terminal of printed filename is

mic16.jpg*nepal_earthquake_death6.png


After combining all the filenames. I store it in database by.

user.photourl = filename
print(user)
db.session.add(user)
db.session.commit()


Here printed output of user in terminal is

<User u'mic16.jpg*nepal_earthquake_death6.png'>


which shows that infomation is loaded correctly.

Now when I do db.session.add(user) followed by db.session.commit(). In user table of the database under photourl column only mic16.jpg part is stored and rest of the part is ommited i.e. part before * is stored.

There is no entry in the database.My database if a MYSQL database and using phpmyadmin. I am reading the database by using.

posts = User.query.order_by(User.date.desc()).limit(5).all()
photourls = []
for i in posts:
photourls.append(i.photourl.split('*'))


Required urls are to be in the photourls. But only a single url is present for each post.

I am just out of my mind and don't have clue of whats going on?

roy roy
Answer

Judging by the size of your photourl string, you want to save several image filenames inside a string separated by an asterisk *. A better alternative would be storing the filenames in a JSON array with each filename as a string.

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    artistname = db.Column(db.String(64))
    photourls = db.Column(JSON)

You can use getlist to upload several image files at once.

def upload():
    uploaded_images = flask.request.files.getlist("file")

The JSON would be stored as shown below.

{
    "photourls":["mic16.jpg", "nepal_earthquake_death6.png"]
}
Comments