title: Using mongo with FLASK and python
body: <p>I am trying to learn python, mongodb and flask and am using the VERY EXCELLENT blog from Miguel Grinberg  who provides a great set of tutorials at  blog.miguelgrinberg.com</p>
  
  <p>I got a small RESTful server working fine but now want to pull stuff from mongo not mysql</p>
  
  <p>I can pull a mongo record out using the code below but am struggling to get it to render. </p>
  
  <p>I have used arrows in the code below to show where I am struggling, lack of experience I think.  Any thoughts would be appreciated.</p>
  
  <pre><code>#!flask/bin/python
  from flask import Flask, jsonify, abort, make_response, url_for
  from pymongo import MongoClient
  
  # connect to mongo database hosted on AWS
  # the script expects the host name to be in  /etc/hosts file
  
  '''
  Set up global variables here
  '''
  mongo_server = "mongo_api"
  mongo_port = "27017"
  mongo_user = "admin"
  mongo_passwd = ":mysecretpassword@"
  connect_string = "mongodb://"+ mongo_user 
                               + mongo_passwd 
                               + mongo_server 
                               + ":" 
                               + mongo_port
  
  app = Flask(__name__)
  
  @app.errorhandler(404)
  def not_found(error):
      return make_response(jsonify( { 'error': 'Notfound' } ), 404)
  
  
  def make_public_page(page):
      new_page = {}
      for field in page:
          if field == 'id':
              new_page['uri'] = url_for('get_page', page_id = page['id'], _external = True)
          else:
              new_page[field] = page[field]
      return new_page
  
  
  
  @app.route('/api/v1.0/pages/&lt;int:page_id&gt;',methods = ['GET'])
  def get_page(page_id):
      '''
      Can connect otherwise exit with message
      '''
      try:
          connection = MongoClient(connect_string)    # equal to &gt; show dbs
      except:
          exit("Error: Unable to connect to the database") # exit with an error
      '''
      connect to database and pull back collections
      '''
      db = connection.test_database # equal to &gt; use test_database                
      pages = db.pages
      page = pages.find_one({"id": int(page_id)})   &lt;------ this pulls back a document
      if page == None:  &lt;---- if a null set comes back then this works great
          abort(404)
      return jsonify( { 'page' : make_public_page(page[0])} ) &lt;- error says its not json
  
  if __name__ == '__main__':
      app.run(debug = True)
  </code></pre>
  
  <p>Any help appreciated, page[0] is the code that's just not working I get a </p>
  
  <p>TypeError: ObjectId('527e17c538320915e9893f17') is not JSON serializable </p>
  
  <p>Thanks in advance</p>
  
  <p>BTW Can't recommend Miguel's mega tutorial enough as a place to start to build stuff</p>