Helpers
Flask-PyMongo 提供一些通用任务的现成方法:
Collection.find_one_or_404(*args, **kwargs)
Find and return a single document, or raise a 404 Not Found exception if no document matches the query spec. See find_one()
for details.
@app.route('/user/<username>')
def user_profile(username):
user = mongo.db.users.find_one_or_404({'_id': username})
return render_template('user.html',
user=user)
PyMongo.send_file(filename, base='fs', version=-1, cache_for=31536000)
Return an instance of the response_class
containing the named file, and implement conditional GET semantics (using make_conditional()
).
@app.route('/uploads/<path:filename>')
def get_upload(filename):
return mongo.send_file(filename)
Parameters:
- filename (str) – the filename of the file to return
- base (str) – the base name of the GridFS collections to use
- version (bool) – if positive, return the Nth revision of the file identified by filename; if negative, return the Nth most recent revision. If no such version exists, return with HTTP status 404.
- cache_for (int) – number of seconds that browsers should be instructed to cache responses
PyMongo.save_file(filename, fileobj, base='fs', content_type=None)
Save the file-like object to GridFS using the given filename. Returns None
.
@app.route('/uploads/<path:filename>', methods=['POST'])
def save_upload(filename):
mongo.save_file(filename, request.files['file'])
return redirect(url_for('get_upload', filename=filename))
Parameters:
- filename (str) – the filename of the file to return
- fileobj (file) – the file-like object to save
- base (str) – base the base name of the GridFS collections to use
- content_type (str) – the MIME content-type of the file. If
None
, the content-type is guessed from the filename usingguess_type()
class flask_pymongo.BSONObjectIdConverter(map)
A simple converter for the RESTful URL routing system of Flask.
@app.route('/<ObjectId:task_id>')
def show_task(task_id):
task = mongo.db.tasks.find_one_or_404(task_id)
return render_template('task.html', task=task)
Valid object ID strings are converted into ObjectId
objects; invalid strings result in a 404 error. The converter is automatically registered by the initialization of PyMongo
with keyword ObjectId
.