使用python操作MongoDB数据库
程序员文章站
2024-03-22 12:34:16
...
python与MongoDB的交互操作
目录
1.使用python操作数据库
'''
@func:使用python脚本对数据库进行创建,插入内容
@aaa@qq.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中
'''
@aaa@qq.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: 新手上路,欢迎斧正.