Python (flask) BLOB 图像、SQLite、Sqlalchemy - 显示图像
Python (flask) BLOB image, SQLite, Sqlalchemy - display image
我试图将图像作为 BLOB 数据类型存储在我的 sqlite 数据库中,然后在我的网页上显示图像,但我不断收到 sqlalchemy 错误(我正在使用 sqlalchemy 作为我的 ORM),错误:
sqlalchemy.exc.StatementError
StatementError: buffer object expected (original cause: TypeError: buffer object expected) u'INSERT INTO room (owner_name, size, description, price, address, owner_number, room_image, university_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' [{'owner_name': u'Thomas Jefferson', 'description': u'Master Bedroom, Non-furnished, toilet attached', 'price': u'RM650/Month', 'room_image': <FileStorage: u'udacity.png' ('image/png')>, 'university_id': 1, 'address': u'Cyber Heights Villa', 'size': u'325sqft', 'owner_number': u'+60111223456'}]
这是我的代码:
1.) 我的数据库设置文件(我在房间里有 BLOB 列 table):
import sys
from sqlalchemy.dialects.sqlite import BLOB
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
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)
@property
def serialize(self):
#Returns object data in easilty serializable format
return{
"name": self.name,
"city": self.city,
"id": self.id,
}
class Room(Base):
__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))
room_image = Column(BLOB)
university_id = Column(Integer, ForeignKey("university.id"))
university = relationship(University)
engine = create_engine("sqlite:///gotroom.db")
Base.metadata.create_all(engine)
2.) 这是我的 python 文件代码,我打算在其中将图像作为 BLOB 上传到 room_image(在 newRoom 函数中是上传照片图像的地方并存储在我房间 table 的 room_image 列中):
#show rooms for a university
@app.route("/university/<int:university_id>/")
@app.route("/university/<int:university_id>/rooms/")
def showRooms(university_id):
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)
#create a new room for a particular university
@app.route("/university/<int:university_id>/rooms/new/", methods=["GET", "POST"])
def newRoom(university_id):
if request.method == "POST":
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"], \
room_image=request.files["roomImage"], 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))
else:
return render_template("newroom.html", university_id=university_id)
3.) 这是创建新房间的表单模板代码"newroom.html"(我必须允许上传图片):
<form action="{{url_for('newRoom', university_id=university_id)}}" method="POST" enctype='multipart/form-data'>
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" name="ownerName" placeholder="Name">
</div>
<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%">
</div>
<input type='file' name='roomImage'>
</div>
</br>
<input type="submit" value="Post Room" class="btn btn-success btn-lg" role="button">
</form>
4.) 这是模板代码,我想在其中显示包括图像在内的所有信息:
</br>
<img src="{{room.room_image}}">
<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>
每当我删除图像时,我都不会收到错误消息,但是当我尝试显示图像时,错误又回来了,请问有人能帮我解决这个问题吗?如果需要,我可以提供更多详细信息或代码
从错误看来,您正在尝试传递错误的类型。我相信 BLOB 需要二进制文件,而您传递的是 png。您可以使用 make_blob()
方法将图像转换为二进制文件。检查 this 页面,应该会有帮助。
我试图将图像作为 BLOB 数据类型存储在我的 sqlite 数据库中,然后在我的网页上显示图像,但我不断收到 sqlalchemy 错误(我正在使用 sqlalchemy 作为我的 ORM),错误:
sqlalchemy.exc.StatementError
StatementError: buffer object expected (original cause: TypeError: buffer object expected) u'INSERT INTO room (owner_name, size, description, price, address, owner_number, room_image, university_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)' [{'owner_name': u'Thomas Jefferson', 'description': u'Master Bedroom, Non-furnished, toilet attached', 'price': u'RM650/Month', 'room_image': <FileStorage: u'udacity.png' ('image/png')>, 'university_id': 1, 'address': u'Cyber Heights Villa', 'size': u'325sqft', 'owner_number': u'+60111223456'}]
这是我的代码: 1.) 我的数据库设置文件(我在房间里有 BLOB 列 table):
import sys
from sqlalchemy.dialects.sqlite import BLOB
from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
Base = declarative_base()
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)
@property
def serialize(self):
#Returns object data in easilty serializable format
return{
"name": self.name,
"city": self.city,
"id": self.id,
}
class Room(Base):
__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))
room_image = Column(BLOB)
university_id = Column(Integer, ForeignKey("university.id"))
university = relationship(University)
engine = create_engine("sqlite:///gotroom.db")
Base.metadata.create_all(engine)
2.) 这是我的 python 文件代码,我打算在其中将图像作为 BLOB 上传到 room_image(在 newRoom 函数中是上传照片图像的地方并存储在我房间 table 的 room_image 列中):
#show rooms for a university
@app.route("/university/<int:university_id>/")
@app.route("/university/<int:university_id>/rooms/")
def showRooms(university_id):
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)
#create a new room for a particular university
@app.route("/university/<int:university_id>/rooms/new/", methods=["GET", "POST"])
def newRoom(university_id):
if request.method == "POST":
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"], \
room_image=request.files["roomImage"], 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))
else:
return render_template("newroom.html", university_id=university_id)
3.) 这是创建新房间的表单模板代码"newroom.html"(我必须允许上传图片):
<form action="{{url_for('newRoom', university_id=university_id)}}" method="POST" enctype='multipart/form-data'>
<div class="row">
<div class="col-md-4">
<input type="text" class="form-control" name="ownerName" placeholder="Name">
</div>
<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%">
</div>
<input type='file' name='roomImage'>
</div>
</br>
<input type="submit" value="Post Room" class="btn btn-success btn-lg" role="button">
</form>
4.) 这是模板代码,我想在其中显示包括图像在内的所有信息:
</br>
<img src="{{room.room_image}}">
<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>
每当我删除图像时,我都不会收到错误消息,但是当我尝试显示图像时,错误又回来了,请问有人能帮我解决这个问题吗?如果需要,我可以提供更多详细信息或代码
从错误看来,您正在尝试传递错误的类型。我相信 BLOB 需要二进制文件,而您传递的是 png。您可以使用 make_blob()
方法将图像转换为二进制文件。检查 this 页面,应该会有帮助。