我想从外部 websocket 获取加密货币数据并将其保存到数据库。为了producer.py从头开始运行,我将其添加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贡献1765条经验 获得超5个赞
您收到此错误是因为在 django 加载完成之前无法访问模型。您的模块尝试在模型尚未加载时访问它们。
要解决您的问题,您应该创建一个 django 管理命令或一个加载和配置 django 的独立脚本,之后您可以毫无问题地运行生产者循环并访问模型。例如
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。
添加回答
举报
0/150
提交
取消