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?