Как мне создать таблицу в базе данных oracle и вставить в нее данные, используя python sqlalchemy? - PullRequest
0 голосов
/ 19 сентября 2018

Мой код такой, как показано ниже:

Мой способ - вставить данные, полученные из отчетов BI-Publisher, в базу данных Oracle.Я хочу добиться этого с помощью Python sqlalchemy Orm.Я пробовал этот код на postgresql, и он работал отлично.В тот момент, когда я пытаюсь запустить это на базе данных Oracle, он выдает ошибку.Пожалуйста, дайте мне знать, если у меня есть какие-то ошибки в моем коде.

import requests
import cx_Oracle
from lxml import etree
from lxml import objectify
from base64 import b64decode
from constants import NS_MAP
import xml.etree.ElementTree as ET
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy import Column, Integer, create_engine, VARCHAR, INTEGER
from sqlalchemy.dialects.oracle.base import BINARY_DOUBLE


Base = declarative_base()
DBSession = scoped_session(sessionmaker())


def database_init():
    engine = create_engine('oracle+cx_oracle://username:password@xyz:1521/SAMPLE')
    DBSession.configure(bind=engine, autoflush=False, expire_on_commit=False)
    Base.metadata.create_all(engine)


global result
item_no = []
item_type = []
case_qty = []
min_minmax_quantity = []
max_minmax_quantity = []
onhand = []
onhand_subinv = []
locator = []
organization_id = []
inventory_item_id = []
creation_date = []
inventory_item_flag = []
inventory_item_status_code = []


class itemOnSync(Base):
    __tablename__ = "SPS_CX_OHNAND_QTY"
    primary_key = Column(Integer, primary_key=True, autoincrement=True)
    ORGANIZATION_ID = Column(BINARY_DOUBLE)
    INVENTORY_ITEM_ID = Column(BINARY_DOUBLE)
    ITEMNO = Column(VARCHAR)
    ITEM_DESCRIPTION = Column(VARCHAR)
    ONHAND_SUBINV = Column(VARCHAR)
    LOCATOR = Column(VARCHAR)
    ONHAND = Column(INTEGER)


def get_empty_envelope():
    envelope = objectify.Element('{{{}}}Envelope'.format(NS_MAP['soapenv']),
                                 nsmap=NS_MAP)
    objectify.SubElement(envelope, '{{{}}}Header'.format(NS_MAP['soapenv']))
    objectify.SubElement(envelope, '{{{}}}Body'.format(NS_MAP['soapenv']))

    return envelope


def report_request():
    file_path = '/~xyz@samirgroup.com/CX/SPS_CX_STOCK_WITH_LOCATOR.xdo'
    report_request_envelope = get_empty_envelope()
    body_element = report_request_envelope['Body']
    run_report_element = objectify.SubElement(body_element,
                                              '{{{}}}runReport'.format(
                                                  NS_MAP['pub']))
    report_request_element = objectify.SubElement(run_report_element,
                                                  '{{{}}}reportRequest'.format(
                                                      NS_MAP['pub']))
    report_request_element.reportAbsolutePath = file_path
    run_report_element.userID = "username"
    run_report_element.password = "password"

    xml_string_payload = etree.tostring(report_request_envelope)
    headers = {
        'Content-Type': 'text/xml',
        'SOAPAction': 'RunReport'
    }
    response = requests.post(
        'https://eerb-test.fa.em3.oraclecloud.com/xmlpserver/services/v2/ReportService',
        data=xml_string_payload,
        headers=headers
    )

    response_element = objectify.fromstring(response.content)
    report_byes = response_element.xpath('//pub:reportBytes',
                                         namespaces=NS_MAP)[0]
    report = b64decode(report_byes.text)
    root = ET.fromstring(report)

    l1 = [{'ITEMNO': None}, {'ITEM_TYPE': None}, {'CASE_QTY': None}, {'MIN_MINMAX_QUANTITY': None},
          {'MAX_MINMAX_QUANTITY': None}, {'ONHAND': None}, {'ONHAND_SUBINV': None}, {'LOCATOR': None},
          {'ORGANIZATION_ID': None}, {'INVENTORY_ITEM_ID': None}, {'CREATION_DATE': None},
          {'INVENTORY_ITEM_FLAG': None},
          {'INVENTORY_ITEM_STATUS_CODE': None}]

    for index, rate in enumerate(root.iter('G_ONHANDQTY')):
        l2 = []
        for child in rate:
            l2.append(dict({child.tag: child.text}))

        check_val = dict((list(i.keys())[0], list(i.values())[0]) for i in l2)
        result = [{list(i.keys())[0]: check_val.get(list(i.keys())[0])} for i in l1]

        for i in result[0].values():
            item_no.append(i)
        for i in result[1].values():
            item_type.append(i)
        for i in result[2].values():
            case_qty.append(i)
        for i in result[3].values():
            min_minmax_quantity.append(i)
        for i in result[4].values():
            max_minmax_quantity.append(i)
        for i in result[5].values():
            onhand.append(i)
        for i in result[6].values():
            onhand_subinv.append(i)
        for i in result[7].values():
            locator.append(i)
        for i in result[8].values():
            organization_id.append(i)
        for i in result[9].values():
            inventory_item_id.append(i)
        for i in result[10].values():
            creation_date.append(i)
        for i in result[11].values():
            inventory_item_flag.append(i)
        for i in result[12].values():
            inventory_item_status_code.append(i)

    return item_no, item_type, case_qty, min_minmax_quantity, max_minmax_quantity, onhand, onhand_subinv, locator, organization_id, inventory_item_id, creation_date, inventory_item_flag


def test_database_dump():
    database_init()
    # DBSession.query(itemOnSync).delete()
    DBSession.commit()
    item_nos, item_types, case_qtys, min_minmax_quantitys, max_minmax_quantitys, onhands, onhand_subinvs, locators, organization_ids, inventory_item_ids, creation_dates, inventory_item_flags = report_request()
    for i in range(len(item_no)):
        items = itemOnSync(
            ORGANIZATION_ID=organization_ids[i],
            INVENTORY_ITEM_ID=inventory_item_ids[i],
            ITEMNO=item_nos[i],
            ITEM_DESCRIPTION=None,
            ONHAND_SUBINV=onhand_subinvs[i],
            LOCATOR=locators[i],
            ONHAND=onhands[i]
        )

        DBSession.add(items)
    DBSession.commit()
    print("Success")


if __name__ == '__main__':
    test_database_dump()

Ошибка:

sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-00906: missing left parenthesis [SQL: '\nCREATE TABLE "SPS_CX_OHNAND_QTY" (\n\tprimary_key INTEGER NOT NULL, \n\t"ORGANIZATION_ID" BINARY_DOUBLE, \n\t"INVENTORY_ITEM_ID" BINARY_DOUBLE, \n\t"ITEMNO" VARCHAR, \n\t"ITEM_DESCRIPTION" VARCHAR, \n\t"ONHAND_SUBINV" VARCHAR, \n\t"LOCATOR" VARCHAR, \n\t"ONHAND" INTEGER, \n\tPRIMARY KEY (primary_key)\n)\n\n'] (Background on this error at: http://sqlalche.me/e/4xp6)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...