使用python操作MongoDB数据库
2018-03-29 17:13
543 查看
python与MongoDB的交互操作
目录
python与MongoDB的交互操作目录
1.使用python操作数据库
2.把爬取数据存入MongoDB中
1.使用python操作数据库
''' @func:使用python脚本对数据库进行创建,插入内容 @binbin_Erices@163.com 代码块符合标准的python3的语法 ''' from pymongo import MongoClient #连接服务器 conn = MongoClient("localhost",27017) #连接Database db = conn.myinfo #获取集合 colllections = db.student #添加document colllections.insert([{"name":"Erices","age":20,"sex":"man","addresee":"beijing"},{"name":"xiaozhang","age":22,"sex":"women",\ "addresee":"shanghai","tel":"3764983790"},{"name":"xiaoming","age":24,"sex":"man","addresee":"shenzhen","isDelete":0}]) conn.close()
代码的执行结果:
使用robo3t-1.2.1进行可视化查看。附:robo3t的下载地址,mongovue对于MongoDB3.0以上版本支持不是很友好。
2.把爬取数据存入MongoDB中
''' @binbin_Erices@163.com use websocket API ''' # from multiprocessing import Pool import json import time from pymongo import MongoClient import websocket def StoreDB(message): print("connecting ---") #connect server conn = MongoClient("localhost",27017) #connect database db = conn.mytest #get collections collection = db.record #add documents collection.insert({"contents":message}) conn.close() def on_open(ws): print('on_open begin....') # // request d = { "event": "subscribe", "channel":"trades" , # "ticker",#trades "pair": "BTCUSD" } ws.send(json.dumps(d)) def on_message(ws,message): message = json.loads(message) # message = json.dumps(message) print(message) # with open("./2.json","a") as f: # f.write(json.dumps(message)) # f.close() StoreDB(message) time.sleep(0.5) def main(url): # url = "wss://stream.binance.com:9443/" #url = "wss://api.bitfinex.com/ws" websocket.enableTrace(True) ws = websocket.WebSocketApp(url, on_message=on_message, on_open=on_open) ws.run_forever(http_proxy_host='127.0.0.1', http_proxy_port=9999) # ws.run_forever() print("End.....") if __name__ == "__main__": url = "wss://api.bitfinex.com/ws" main(url)
执行结果:
PS: 新手上路,欢迎斧正.
相关文章推荐
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- 使用python操作串口
- 使用Python操作XLS文件(wps中叫et)
- MySQLdb for Python使用指南/Python的数据库操作
- [Python]MySQLdb for Python使用指南/Python的数据库操作
- 【转】使用Python操作XLS文件
- 使用python操作excel
- 使用Python二进制与十进制之间的转化,可以操作浮点数!
- Memcached 安装、使用(Python操作)以及常用方法
- 使用Python(comtypes)操作ArcGis(ArcObject)的第一步:安装模块到gen文件夹中
- 使用Python 2.7 CURD 操作非关系型数据库MongoDB
- python操作Excel读写(使用xlrd和xlrt)
- 使用Python操作注册表
- 使用Python操作注册表
- 使用Python操作注册表
- python操作Excel读写(使用xlrd和xlrt)
- 使用Python的Command Line操作Excel的Macro
- 使用Python自动化Windows界面操作
- MySQLdb for Python使用指南/Python的数据库操作
- Python3.0 我的DailyReport 脚本(一) 使用COM操作Excel