我是燒瓶的新手,我有一個關于flask-sqlalchemy. 我的程式使用dropzone.js并上傳多張圖片,目標是將圖片檔案的 url 作為字串串列保存到資料庫以供以后訪問。
我創建了一個串列,然后將 url 附加到該串列中,然后將該串列型別轉換為字串,例如。str(file_urls),并像這樣將其添加到模型的欄位中,
foo = FooForm()
file_urls = list()
for uploaded_file in request.files.getlist('file'):
filename = secure_filename(uploaded_file.filename)
if filename != '':
file_ext = os.path.splitext(filename)[1]
if file_ext not in app.config['UPLOAD_EXTENSIONS']:
return "Invalid Image", 400
uploaded_file.save(os.path.join(app.config['UPLOAD_PATH'], filename))
file_urls.append(filename)
if foo.validate_on_submit():
_post = Post(image_folder=str(file_urls)) # assuming it's the only column present in the table
db.session.add(_post)
db.session.commit()
視圖結構看起來像,
@app.route('/post/<int:some_post_id>')
def post_fn(some_post_id):
# relevent code here
file_urls = eval(Post.image_folder) #I get error here stating that," TypeError: eval() arg 1 must be a string, bytes or code object"
return render_template('a_template.html', file_urls=file_urls)
模型 :
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
image_folder = db.Column(db.String(120), nullable=False)
def __repr__(self):
return '{}'.format(self.image_folder)
在這種情況下,如何檢索存盤在變數 image_folder 中的字串,以便再次使用 eval 將其轉換為串列?
請問有人嗎?
uj5u.com熱心網友回復:
根據您的模型的設定方式,您必須執行以下操作:
@app.route('/post/<int:some_post_id>')
def post_fn(some_post_id):
# irrelevent code here
post = Post.query.filter_by(id=id) # Get the post from the database with the id from the route
file_urls = eval(post.image_folder)
return render_template('a_template.html', file_urls=file_urls)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/520056.html
