python gridfs的存储方法_python - 检索要从Flask发送的GridFS中的文件? - 堆栈内存溢出...

该代码当前适用于从flask应用程序上传文件。 用户给我一个整数和一个文件。 然后,我将文件存储在GridFS中。 现在,如果有人尝试获取该文件,则如果他们知道特定的整数,则gridfs需要将其还给他们。 当他们转到URL / uploads /

在/uploads/内部,我们得到了编号并调用readfile() ,它将所需的文件写入uploads/文件夹。 但是,我们如何才能获取该文件并将其发送呢? 我这样做正确吗? 大概以后我需要从磁盘上删除文件。 但是我没有要在upload()函数中发送或取消链接的file对象。

我还有另一个问题。 我希望mongodb在存储它们之后大约10分钟删除这些条目,我该怎么做。 我知道我应该给gridfs一个特殊的领域,我只是不知道具体如何。

app.config['UPLOAD_FOLDER'] = 'uploads/'

db = "spaceshare"

def get_db(): # get a connection to the db above

conn = None

try:

conn = pymongo.MongoClient()

except pymongo.errors.ConnectionFailure, e:

print "Could not connect to MongoDB: %s" % e

sys.exit(1)

return conn[db]

# put files in mongodb

def put_file(file_name, room_number):

db_conn = get_db()

gfs = gridfs.GridFS(db_conn)

with open('uploads/' + file_name, "r") as f:

gfs.put(f, room=room_number)

# read files from mongodb

def read_file(output_location, room_number):

db_conn = get_db()

gfs = gridfs.GridFS(db_conn)

_id = db_conn.fs.files.find_one(dict(room=room_number))['_id']

#return gfs.get(_id).read()

with open(output_location, 'w') as f:

f.write(gfs.get(_id).read())

@app.route('/')

def home():

return render_template('index.html')

@app.route('/upload',methods=['POST'])

def upload():

#get the name of the uploaded file

file=request.files['file']

#print "requested files"

space=request.form['space']

# if the file exists make it secure

if file and space: #if the file exists

#make the file same, remove unssopurted chars

filename=secure_filename(file.filename)

#move the file to our uploads folder

file.save(os.path.join(app.config['UPLOAD_FOLDER'],filename))

put_file(filename,space)

# remove the file from disk as we don't need it anymore after database insert.

os.unlink(os.path.join( app.config['UPLOAD_FOLDER'] , filename))

# debugging line to write a file

f = open('debug.txt', 'w')

f.write('File name is '+filename+' or ' +file.name+' the space is :'+ str(space) )

return render_template('index.html', filename = filename ,space = space) ##take the file name

else:

return render_template('invalid.html')

@app.route('/uploads/', methods=['GET'])

def return_file(spacenum):

read_file(app.config['UPLOAD_FOLDER'] ,spacenum)

send_from_directory(app.config['UPLOAD_FOLDER'], filename)

return render_template('thanks.html' , spacenum = spacenum)

这是我使用过的源代码以及我从中构建此代码的示例以及我的完整源代码。 预先感谢您的所有帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值