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()

 

转载于:https://www.cnblogs.com/plan/p/4972136.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值