Skip to content

Instantly share code, notes, and snippets.

@tzuryby
Created April 15, 2013 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzuryby/5385889 to your computer and use it in GitHub Desktop.
Save tzuryby/5385889 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import re
import json
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado import gen
from tornado.options import define, options
import motor
define("port", default=9090, help="dev port 9090", type=int)
define("host", default="localhost", help="dev host localhost only", type=str)
MONGO_URI = "mongodb://localhost"
def motor_connection():
return motor.MotorClient(MONGO_URI).open_sync().test_db
# this decorator catches exceptions of request handlers
# and responds with a simple error page instead of sending Tornado traceback stack to the browser
def request_handler(method):
def wrapper(self, *args, **kwargs):
try:
return method(self, *args, **kwargs)
except:
self.write("Error!")
return wrapper
def prepare_to_json(doc):
doc["_id"] = str(doc["_id"])
return doc
class MotorTesterRequestHandler(tornado.web.RequestHandler):
@property
def current_account(self):
return self.get_current_account()
@property
def db(self):
return self.settings['motor_db']
def push_json(self, data):
data = json.dumps(data)
self.set_header('Content-Type', 'application/json')
self.write(data)
self.finish()
class TestHandler(MotorTesterRequestHandler):
@request_handler
def get(self):
self.write("<h1>Hello World</h1>\n")
@request_handler
@gen.engine
@tornado.web.asynchronous
def post(self):
ga = self.get_argument
data_filter = ga("filter")
limit_number = int(ga("limit", 10))
# toggle comment following pair of lines to see the issue
# when providing {foo: data_filter} -- that's an error, as foo is not defined
# only timeout breaks.
# cursor = self.db.sample_collection.find({foo: data_filter}).limit(limit_number)
cursor = self.db.sample_collection.find({"foo": data_filter}).limit(limit_number)
documents = yield motor.Op(cursor.to_list)
self.push_json(map(prepare_to_json, documents))
class MotorApplication(tornado.web.Application):
def __init__(self):
settings = dict(
autoescape=None,
debug=True,
motor_db = motor_connection()
)
# paths which available for ui client only.
url_mapper = [
(r"/", TestHandler),
]
tornado.web.Application.__init__(self, url_mapper, **settings)
def main():
tornado.options.parse_command_line()
console_server = tornado.httpserver.HTTPServer(MotorApplication())
console_server.listen(options.port, options.host)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
@tzuryby
Copy link
Author

tzuryby commented Apr 15, 2013

# prepare DB
mongo> use test_db
mongo> db.sample_collection.insert({foo:"1"})
mongo> db.sample_collection.find()
{ "_id" : ObjectId("516b8dd1c3a5397d1469d152"), "foo" : "1" }

# test the server
$ curl localhost:9090 --data filter=2
[]
$ curl localhost:9090 --data filter=1
[{"_id": "516b8dd1c3a5397d1469d152", "foo": "1"}

@tzuryby
Copy link
Author

tzuryby commented Apr 15, 2013

The problem:

Toggle comment lines 76-77 and see no error for calling find with {foo: data_filter} instead of {"foo": data_filter}.

cursor = self.db.sample_collection.find({foo: data_filter}).limit(limit_number)
# cursor = self.db.sample_collection.find({"foo": data_filter}).limit(limit_number)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment