zoukankan      html  css  js  c++  java
  • tornado_mongodb 连接和使用

    tornado,mongodb 连接和使用,开始使用tornado3.2,mongodb2.6,pymongo-3.03遇到不少的麻烦。因为新版tornado与老版本的代码有很多变化,mongodb根本没法连接,这里借Shekhar Gulati编写的代码终于看清楚这个框架怎么连接mongodb了。非常谢谢Shekhar Gulati!

    tornadoapp.py文件

    import os
    from tornado import ioloop,web
    from tornado.escape import json_encode
    from pymongo import MongoClient
    import json
    from bson import json_util
    from bson.objectid import ObjectId
    
    
    MONGODB_DB_URL = os.environ.get('OPENSHIFT_MONGODB_DB_URL') if os.environ.get('OPENSHIFT_MONGODB_DB_URL') else 'mongodb://localhost:27017/'
    MONGODB_DB_NAME = os.environ.get('OPENSHIFT_APP_NAME') if os.environ.get('OPENSHIFT_APP_NAME') else 'getbookmarks'
    
    client = MongoClient(MONGODB_DB_URL)
    db = client[MONGODB_DB_NAME]
    
    class IndexHandler(web.RequestHandler):
        def get(self):
            self.render("index.html")
    
    class StoriesHandler(web.RequestHandler):
        def get(self):
            stories = db.stories.find()
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps(list(stories),default=json_util.default))
            
    
        def post(self):
            story_data = json.loads(self.request.body)
            story_id = db.stories.insert(story_data)
            print('story created with id ' + str(story_id))
            self.set_header("Content-Type", "application/json")
            self.set_status(201)
            
    
    class StoryHandler(web.RequestHandler):
        def get(self , story_id):
            story = db.stories.find_one({"_id":ObjectId(str(story_id))})
            self.set_header("Content-Type", "application/json")
            self.write(json.dumps((story),default=json_util.default))
    
    
    settings = {
        "template_path": os.path.join(os.path.dirname(__file__), "templates"),
        "static_path": os.path.join(os.path.dirname(__file__), "static"),
        "debug" : True
    }
    
    application = web.Application([
        (r'/', IndexHandler),
        (r'/index', IndexHandler),
        (r'/api/v1/stories',StoriesHandler),
        (r'/api/v1/stories/(.*)', StoryHandler)
    ],**settings)
    
    if __name__ == "__main__":
        application.listen(8081)
        ioloop.IOLoop.instance().start()

    app.py文件

    #!/usr/bin/env python
    
    #
    # This file may be used instead of Apache mod_wsgi to run your python
    # web application in a different framework.  A few examples are
    # provided (cherrypi, gevent), but this file may be altered to run
    # whatever framework is desired - or a completely customized service.
    #
    import imp
    import os
    
    try:
       zvirtenv = os.path.join(os.environ['OPENSHIFT_PYTHON_DIR'],
                               'virtenv', 'bin', 'activate_this.py')
       execfile(zvirtenv, dict(__file__ = zvirtenv) )
    except IOError:
       pass
    
    #
    # IMPORTANT: Put any additional includes below this line.  If placed above this
    # line, it's possible required libraries won't be in your searchable path
    #
    
    
    #
    #  main():
    #
    if __name__ == '__main__':
       ip   = os.environ['OPENSHIFT_PYTHON_IP']
       port = int(os.environ['OPENSHIFT_PYTHON_PORT'])
       app = imp.load_source('application', 'tornadoapp.py')
    
       app.application.listen(port , ip)
       app.ioloop.IOLoop.instance().start()
  • 相关阅读:
    css区分ie6,7,ff
    轮播插件--可支持视频拖拽和可视区播放
    json无限树----几个月前写的插件
    WEBGL学习笔记二
    记录一些坑
    webGL学习笔记一
    Angular模态框
    Angular指令实践之type等于text的input星号输入
    Angular内置指令
    Angular指令一
  • 原文地址:https://www.cnblogs.com/plan/p/4972136.html
Copyright © 2011-2022 走看看