I'm trying to save the data that send using django channel and postgresql.
consumers.py
async def connect(self):
event = eventhubreader.EventReader()
async def cb(partition, events):
data = events[len(events)-1]
await self.send(json.dumps({'value': data.body_as_json()}))
now = datetime.now()
dataFormat = {"IotData": {"temperature": data.body_as_json()["temperature"], "humidity": data.body_as_json()["humidity"]}, "MessageDate": now.strftime("%d/%m/%Y %H:%M:%S"), "DeviceId": data.body_as_json()['deviceId']}
saverecord = Rawdata()
saverecord.ref_waterplant = random.randint(20, 25)
saverecord.created_at = dataFormat['MessageDate']
saverecord.is_live = True
saverecord.save()
print(dataFormat)
await self.accept()
models.py
class Rawdata(models.Model):
ref_waterplant = models.CharField(max_length=100)
created_at = models.DateField()
is_live = True
class Meta:
db_table = "rawdata"
error
An error occurred while receiving. The exception is SynchronousOnlyOperation('You cannot call this from an async context - use a thread or sync_to_async.').
CodePudding user response:
You can make seperate function for saving entry in database and call and you can return also if you want
from channels.db import database_sync_to_async
async def connect(self):
await self.save_entry()
#more code----
@database_sync_to_async
def save_entry(self):
saverecord = Rawdata()
saverecord.ref_waterplant = random.randint(20, 25)
saverecord.created_at = dataFormat['MessageDate']
saverecord.is_live = True
saverecord.save()
return