0

I need to save some data using SQLAlchemy. The Insert statement works fine when the sqlalchemy create_engine is initialize inside the file where the function lives

from sqlalchemy import create_engine
from sqlalchemy.sql import text
engine = create_engine('sqlite:///db.sqlite3')

// this will work

@csrf_exempt
def save(request):
     payload = json.loads(request.body.decode('utf-8'))['data']
     payload = payload['body']
     response = cu.call("externalapi/someendpoint",
                   payload=json.dumps(payload), method="POST")
     id = response['id']
     statement = f"""INSERT INTO consignments(consignment_id) VALUES({id})"""
     with engine.connect as con:
          con.execute(statement)
    

// this will not work

from utils import create_consignment
@csrf_exempt
def save(request):
     payload = json.loads(request.body.decode('utf-8'))['data']
     payload = payload['body']
     response = cu.call("externalapi/someendpoint",
                   payload=json.dumps(payload), method="POST")
     id = response['id']
     statement = f"""INSERT INTO consignments(consignment_id) VALUES({id})"""
     create_consignment(statement)

   //this will throw error 
  `payload = json.loads(request.body.decode('utf-8'))['data']
   AttributeError: 'str' object has no attribute 'body'`
   // If I remove the `create_consignment`, the error gone

So the create_consignment method, is just lines of codes extracted to make it more reusable

utils/create_consignment.py

  import sqlalchemy as db
  from sqlalchemy.sql import text
 
  engine = db.create_engine('sqlite:///db.sqlite3',
                      connect_args={'check_same_thread': False})

  def create_consignment(stmt):
     with engine.connect() as con:
        statement = text(stmt)

        con.execute(statement)
    

Any Idea whats going on and how to prevent this error?

ira
  • 534
  • 1
  • 5
  • 17
  • It seems your change for Sqlalchemy broke the dispatch logic of Django. You need to provide a [mre] and debugging details, including the server log with a stack trace. – relent95 Oct 19 '22 at 15:30
  • I don't see how the reported error can relate to the `create_consignment` function. There's something else going on here. As relent95 requests, please provide a [mre]. Moreover, Django alrady provides machinery for executing [raw SQL](https://docs.djangoproject.com/en/4.1/topics/db/sql/), you shouldn't need to introduce SQLAlcheny. – snakecharmerb Oct 29 '22 at 10:16

0 Answers0