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()
tornado_mongodb 连接和使用的更多相关文章
- nodejs进阶(6)—连接MySQL数据库
1. 建库连库 连接MySQL数据库需要安装支持 npm install mysql 我们需要提前安装按mysql sever端 建一个数据库mydb1 mysql> CREATE DATABA ...
- SQL Server 无法连接到服务器。SQL Server 复制需要有实际的服务器名称才能连接到服务器。请指定实际的服务器名称。
异常处理汇总-数据库系列 http://www.cnblogs.com/dunitian/p/4522990.html SQL性能优化汇总篇:http://www.cnblogs.com/dunit ...
- Linux 开机时网络自动连接
简单版本: cd /etc/sysconfig/network-scripts/ vi ifcfg-enoXXX 输入:reboot重启 或者输入:service network restart ...
- 在ubuntu16.10 PHP测试连接MySQL中出现Call to undefined function: mysql_connect()
1.问题: 测试php7.0 链接mysql数据库的时候发生错误: Fatal error: Uncaught Error: Call to undefined function mysqli_con ...
- 【初学python】使用python连接mysql数据查询结果并显示
因为测试工作经常需要与后台数据库进行数据比较和统计,所以采用python编写连接数据库脚本方便测试,提高工作效率,脚本如下(python连接mysql需要引入第三方库MySQLdb,百度下载安装) # ...
- 一起学微软Power BI系列-使用技巧(1)连接Oracle与Mysql数据库
说起Oracle数据库,以前没用过Oracle不知道,但是这1年用Oracle后,发现真的是想狂吐槽,特别是那个.NET驱动和链接字符串,特别奇葩.总归是和其他数据库不一样,标新立异,不知道为何.另外 ...
- 使用SecureCRT连接虚拟机(ubuntu)配置记录
这种配置方法,可以非常方便的操作虚拟机里的Linux系统,且让VMware在后台运行,因为有时候我直接在虚拟机里操作会稍微卡顿,或者切换速度不理想,使用该方法亲测本机效果确实ok,特此记录. Secu ...
- c# 字符串连接使用“+”和string.format格式化两种方式
参考文章:http://www.liangshunet.com/ca/201303/218815742.htm 字符串之间的连接常用的两种是:“+”连接.string.format格式化连接.Stri ...
- 如何使用本地账户"完整"安装 SharePoint Server 2010+解决“New-SPConfigurationDatabase : 无法连接到 SharePoint_Config 的 SQL Server 的数据 库 master。此数据库可能不存在,或当前用户没有连接权限。”
注:目前看到的解决本地账户完整安装SharePoint Server 2010的解决方案如下,但是,有但是的哦: 当我们选择了"完整"模式安装SharePointServer201 ...
随机推荐
- 不能用con作为类名
A class file was not written. The project may be inconsistent, if so try refreshing this project and ...
- ZOJ 2771
Description Considering a light entering three adjacent planes of glass. At any meeting surface, t ...
- 通过iTop Webservice接口丰富OQL的功能
通过Python调用iTop的Webservice接口: #!/usr/bin/env python #coding: utf-8 import requests import json itopur ...
- (四)G1 garbage collector
g1专为大内存,多内核机型设计.可以兼顾高吞吐量和低暂停时间. g1将堆分为多个相同大小内存块,并发的标记线程,使得g1掌握了各个内存块的活对象数量, 内存回收阶段,g1根据用户指定的暂停时间,选择部 ...
- springboot+druid
最近项目需要搭建新工程,打算使用微服务的形式搭建便于后期拓展.看了一圈发现springboot易于搭建,配置简单,强化注解功能,"just run". Spring Boot ma ...
- apachetop 实时监控apache指定日志
编译安装,压缩包戳我下载 帮助文档 # apachetop -h ApacheTop v0.12.6 - Usage: File options: -f logfile open logfile (a ...
- 分析器错误消息: 未能加载类型“Automation.Web.MvcApplication”。
常见原因1 : 可能是自己手动修改了项目 ==>属性==>生成的输出路径 ,导致版本不兼容 常见员因2 : Global的 命名空间 与 项目的命名空间 不一致 常见原因3 : 查看 ...
- WordPress多站点获取当前博客信息
http://www.utubon.com/1495/wordpress-multisite-get-current-bolg-info global $current_blog; 它的返回结果是: ...
- HTML中head里的内容经浏览器解析后全到body里了
HTML中head里的内容经浏览器解析后全到body里了 修改完代码后,用chrome审查元素,head里的内容都到body中去了 http://bbs.csdn.net/topics/3802586 ...
- shell中{}的妙用
shell中${}的妙用 1. 截断功能 ${file#*/}: 拿掉第一条/及其左边的字符串:dir1/dir2/dir3/my.file.txt ${file##*/}: 拿 ...