阿波羅的戰(zhàn)車
2023-08-22 10:46:44
我想從外部 websocket 獲取加密貨幣數(shù)據(jù)并將其保存到數(shù)據(jù)庫。為了producer.py從頭開始運(yùn)行,我將其添加INSTALLED_APPS到settings.py:INSTALLED_APPS = [ 'crypto.spot.producer',]producer.py是:from .models import Spotasync def message(u, t, interval, timeout): async with websockets.connect(uri=u + '?token=' + t, ping_interval=interval, ping_timeout=timeout) as websocket: await websocket.send(json.dumps({"id": "4848226", "type": "subscribe", "topic": "/market/ticker:all", "response": True})) while True: response = await websocket.recv() result = json.loads(response) ''' write result to django model (Spot) '''while True: response = r.post('https://api.kucoin.com/api/v1/bullet-public') payload = json.loads(response.text) uri = payload['data']['instanceServers'][0]['endpoint'] token = payload['data']['token'] ping_interval = payload['data']['instanceServers'][0]['pingInterval'] ping_timeout = payload['data']['instanceServers'][0]['pingTimeout'] asyncio.get_event_loop().run_until_complete(message(uri, token, ping_interval, ping_timeout)) asyncio.get_event_loop().run_forever()
1 回答

POPMUISE
TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個贊
您收到此錯誤是因?yàn)樵?django 加載完成之前無法訪問模型。您的模塊嘗試在模型尚未加載時訪問它們。
要解決您的問題,您應(yīng)該創(chuàng)建一個 django 管理命令或一個加載和配置 django 的獨(dú)立腳本,之后您可以毫無問題地運(yùn)行生產(chǎn)者循環(huán)并訪問模型。例如
producer.py模塊:
import sys, os, django
sys.path.append("/path/to/your/project")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your-project.settings")
django.setup()
from <your-app>.models import Spot
.... Your script
不要忘記從 中刪除模塊 ( crypto.spot.producer) INSTALLED_APPS。
添加回答
舉報(bào)
0/150
提交
取消