mercredi 15 juin 2016

Store Image in Database :: Issue :: Python Flask

Currently I working on uploading image and display the image via python flask . The two features looks something like this:

import os
import os.path
from flask import Flask, request, redirect, url_for, send_from_directory,render_template
from flask_sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager, login_user , logout_user , current_user , login_required, UserMixin

app = Flask(__name__, static_folder="images")
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://EugeneTan:root@localhost/pelican' #EugeneTan:root(username:password)
app.config['SECRET_KEY'] = 'ultra-secret'
app.config['SECURITY_REGISTERABLE'] = True
db = SQLAlchemy(app)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))

class Image(db.Model):
    __tablename__ = 'image'
    id = db.Column('image_id', db.Integer, primary_key=True)
    ImageName = db.Column('ImageName', db.String(1000))


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

@app.route("/")
def index():
    return render_template("upload.html")

@app.route("/upload",methods=['POST'])
def upload():
    target = os.path.join(APP_ROOT,'images/')
    print(target)#debugging purposes

    #make sure there is no redundant folder 
    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("file"):#return a list of file name 
        print (file)
        filename = file.filename #obtain the current/ desired filename from the list
        destination = "/".join([target, filename])
        print (destination)
        file.save(destination)

    return render_template("complete.html",image_name=filename)

@app.route('/upload/<filename>')
def send_image(filename):
    return send_from_directory("images" , filename)

@app.route('/gallery')
def get_gallery():
    image_name = os.listdir("./images" )    
    print(image_name)
    return render_template("gallery.html",image_name=image_name)


if __name__ == '__main__':
    app.debug = True
    app.run()

this is the html page for upload:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset = "UTF-8">
    <title>Upload</title>
</head>
<body>
    <h1>File Uploader</h1>
    <form id="upload-form" action="{{url_for('upload')}}" method="post" enctype="multipart/form-data" >


        <input type = "file" name="file" accept="image/*" multiple>
        <input type= "submit" value="Enter">
    </form>

</body>
</html>

Now, if you notice , I already create a table called image, and there are only two attributes inside the table. After that I wish to store the name of the image(filename) inside the table. So, I started to do some changes of my code. Something like this:

@app.route("/upload",methods=['POST'])
def upload():
    target = os.path.join(APP_ROOT,'images/')
    print(target)#debugging purposes

    #make sure there is no redundant folder 
    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist("file"):#return a list of file name 
        print (file)
        filename = file.filename#obtain the current/ desired filename from the list
        destination = "/".join([target, filename])
        print (filename)
        print (destination)
        file.save(destination)
        **up = Image(request.form['ImageName'])**
        **db.session.add()**
        **db.session.commit()**
    return render_template("complete.html",image_name=filename)

In html, I modified the code into like this:

<input type = "file" name="ImageName" accept="image/*" multiple>

This approach will give me an UnboundLocalError I have come across the blob and bytea, and I dont want apply overhere. All i wanted to do is I want to store name of the image inside the table that I had created! Some one here please point out the error that i made over here or please provide me alternative in order to store image in database. Thanks!

Aucun commentaire:

Enregistrer un commentaire