Flask-upload,图片上传(无法渲染图片)

时间:2015-04-21 14:21:51

标签: flask sqlalchemy flask-sqlalchemy flask-admin flask-uploads

我正在尝试使用flask-uploads显示图像。我在我的数据库设置文件(模型)中定义了我的上传表,我正在使用SQLAlchemy。  这是我的数据库模型定义如下:(完整的代码可以在link到我的github repo中找到)

import sys
import os
from sqlalchemy import  Boolean, Float, Text
#importing classes from sqlalchemy module
from sqlalchemy import Column, ForeignKey, Integer, String, TEXT

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import relationship


from sqlalchemy import create_engine, MetaData


Base = declarative_base()


class User(Base):

    __tablename__ = "user"

    id = Column(Integer, primary_key=True)
    name = Column(String(80), nullable=False)
    email = Column(String(50), nullable=False)
    picture = Column(String(250))


class University(Base):


    __tablename__ = "university"

    #column definitions for the university table
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    city = Column(String(80), nullable=False)
    user_id = Column(Integer, ForeignKey("user.id"))
    user = relationship(User)
    upload_id = Column(Integer, ForeignKey("upload.id"))
    upload = relationship(Upload)



class Upload(Base):

    __tablename__ = "upload"

    id = Column(Integer, autoincrement=True, primary_key=True)
    name = Column(TEXT(convert_unicode=True))
    url = Column(TEXT(convert_unicode=True))

class Room(Base):
    """
    this class corresponds to the table representation
    of room which is in the database
    """

    __tablename__ = "room"

    #column definitions for the room table
    owner_name = Column(String(90), nullable=False)
    id = Column(Integer, primary_key=True)
    size = Column(String(60))
    description = Column(String(250))
    price = Column(String(10))
    address = Column(String(250))
    owner_number = Column(String(15))
    university_id = Column(Integer, ForeignKey("university.id"))
    university = relationship(University)
    user_id = Column(Integer, ForeignKey("user.id"))
    user = relationship(User)
    upload_id = Column(Integer, ForeignKey("upload.id"))
    upload = relationship(Upload)


engine = create_engine("sqlite:///gotroomwithusers.db")


Base.metadata.create_all(engine)

这是我上传图片的路线:

import os
from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.storage import get_default_storage_class
from flask.ext.uploads import delete, init, save, Upload


#import module for ORM
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from database_setup import Base, University, Room, Upload


#create an instance of Flask class with the name
#of the runnung application as the argument
app = Flask(__name__)
#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
app.config['DEFAULT_FILE_STORAGE'] = 'filesystem'
app.config['UPLOADS_FOLDER'] = os.path.realpath('.') + '/static/'
app.config['FILE_SYSTEM_STORAGE_FILE_VIEW'] = 'static'
init(SQLAlchemy(app), get_default_storage_class(app))



#create connection to database
engine = create_engine("sqlite:///gotroomwithusers.db")
Base.metadata.bind=engine
DBSession = sessionmaker(bind=engine)
session=DBSession()

@app.route("/university/<int:university_id>/rooms/new/", methods=["GET", "POST"])
def newRoom(university_id):
    if request.method == "POST":
        save(request.files['upload'])
        aNewRoom = Room(owner_name=request.form["ownerName"], size=request.form["roomSize"]\
                       , description=request.form["roomDescription"], price=request.form["roomPrice"]\
                        , address=request.form["adress"], owner_number=request.form["phoneNum"], \
                        university_id=university_id)

        session.add(aNewRoom)
        session.commit()

        #feedback to user
        flash("New Room Created")       


        return redirect(url_for("showRooms", university_id=university_id, uploads=uploads))
    else:
        return render_template("newroom.html", university_id=university_id)

这是上述路线的html代码:

                                   

    <div class="col-md-3">
        <input type="text" class="form-control" name="phoneNum" placeholder="Contact Number">
    </div>

    <div class="col-md-5">
        <input type="text" class="form-control" name="adress" placeholder="Address">
    </div>
</div><!--first row-->
</br>
<div class="row">
    <div class="col-md-2">
        <input type="text" class="form-control" name="roomSize" placeholder="Room Size">
    </div>

    <div class="col-md-2">
        <input type="text" class="form-control" name="roomPrice" placeholder="Room Price/Month">
    </div>
</div><!--second row-->
</br>
<div class="row">
    <div class="col-md-4" style="height: 100px">
        <input type="text" class="form-control" name="roomDescription" placeholder="Room Details" style="height: 100%">
        </br>
        <input type="file" name="upload">
    </div>

这是我希望相应显示各个图像的路线:

@app.route("/university/<int:university_id>/")
@app.route("/university/<int:university_id>/rooms/")
def showRooms(university_id):
    uploads = session.query(Upload).filter_by(id=university_id)one()
    university = session.query(University).filter_by(id=university_id).one()
    rooms = session.query(Room).filter_by(university_id=university_id).all()
    return render_template("rooms.html", rooms=rooms, university=university, uploads=uploads)

这是上述路线的hmtl代码:

{% for room in rooms %}
    <div class="row">

        <div class="col-md-12">
            {{upload.name}}
            <strong>Owner Name</strong>: {{room.owner_name}}

            </br>
            <strong>Contact Number</strong>: {{room.owner_number}}
            </br>
            <strong>Home Address</strong> : {{room.address}}
            </br>
            <strong>Room Price</strong> : {{room.price}}
            </br>
            <strong>Room Size</strong>  : {{room.size}}
            </br>
            <strong>Room Description</strong>: {{room.description}}
       <div>

       </br>

       <hr>             
{% endfor %}

我可以看到图像保存在我的静态文件夹中,但无法在我的网页上呈现。我一直收到错误:

OperationalError: (OperationalError) no such table: 
upload u'INSERT INTO upload (name, url) VALUES (?, ?)' 
(u'el-caffinito_3.jpg', u'/static/el-caffinito_3.jpg')

如果需要,我可以提供完整的代码

0 个答案:

没有答案