我是一名自学成才的新手,所以请耐心等待。我正在尝试创建一个允许用户上传其图像的网站。有了另一个用户的耐心,我能够得到一些答案,说明如何创建并允许用户将他们的图像上传到openshift上的数据驱动器上。但是,现在我需要能够将图像路径或URL存储到postgresql数据库(稍后可以调用),以便每个用户都能够跟踪他们上传的图像。我目前因此而受阻。 以下是我认为在回答这个问题时起着重要作用的代码片段:
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column('todo_id', db.Integer, primary_key=True)
title = db.Column(db.String(60))
text = db.Column(db.String)
done = db.Column(db.Boolean)
pub_date = db.Column(db.DateTime)
user_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
image_url = db.Column(db.String)
def __init__(self, title, text, image_url):
self.title = title
self.text = text
self.image_url = image_url
self.done = False
self.pub_date = datetime.utcnow()
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
@app.route('/upload', methods=['POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
# Redirect the user to the uploaded_file route, which
# will basicaly show on the browser the uploaded file
return redirect(url_for('uploaded_file',
filename=filename))
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
@app.route('/new', methods=['GET', 'POST'])
@login_required
def new():
if request.method == 'POST':
if not request.form['title']:
flash('Title is required', 'error')
elif not request.form['text']:
flash('Text is required', 'error')
else:
todo = Todo(request.form['title'], request.form['text'])
todo.user = g.user
db.session.add(todo)
db.session.commit()
flash('Todo item was successfully created')
return redirect(url_for('index'))
return render_template('new.html')
我所拥有的当前代码由各种教程和示例拼凑而成。 目前,我正在尝试合并“Todo”数据库,“上传”功能和“新”功能,但收效甚微。使用我所拥有的一点点知识,我只添加了“image_url”部分,其中将是一个用于容纳图像路径的列。如果有人能对这个难题有所了解,我将不胜感激。万分感谢。
尊敬, 最大