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.

  1. @app.route('/user/<username>')
  2. def user_profile(username):
  3. user = mongo.db.users.find_one_or_404({'_id': username})
  4. return render_template('user.html',
  5. 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()).

  1. @app.route('/uploads/<path:filename>')
  2. def get_upload(filename):
  3. 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.

  1. @app.route('/uploads/<path:filename>', methods=['POST'])
  2. def save_upload(filename):
  3. mongo.save_file(filename, request.files['file'])
  4. 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 using guess_type()

class flask_pymongo.BSONObjectIdConverter(map)

A simple converter for the RESTful URL routing system of Flask.

  1. @app.route('/<ObjectId:task_id>')
  2. def show_task(task_id):
  3. task = mongo.db.tasks.find_one_or_404(task_id)
  4. 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.