2

The program that I created will be used to parse xml files and put it the parse datas in the database. Though my code is okay now and running, my instructor has a comment in my code, BTW this is my code:

import os
import time
import MySQLdb
import ConfigParser
import elementtree.ElementTree as ET


def update_database(article_code, date_received, s100rsd, remark_text, db):
    cur = db.cursor()
    try:
        cur_query = cur.execute("""INSERT INTO tblS100CurrentListing """
                                """(article_Code, dateReceived, s100RSD, remarks) VALUES (%s, %s, %s, %s) """
                                """ON DUPLICATE KEY UPDATE revisedRSD = %s, remarks = %s """,
                                (article_code, date_received, s100rsd, remark_text, s100rsd, remark_text))
        db.commit()
    except MySQLdb.Error, e:
        print "An error has been passed %s" %e
        db.rollback
    rows_affected = cur.rowcount
    if rows_affected > 0:
        print "Changes made in the database"
    else:
        print "Nothing is change in  the database"


def parse_xml(source_path, xml_file):
    # Alvin: !!! globals?
    global article_code
    global date_received
    global s100rsd
    global remark_text
    article_code = xml_file.split('.')[0]
    tree = ET.parse(xml_file)
    root = tree.getroot()
    order = root.find('order')
    order_time = order.find('time')
    year = order_time.attrib['yr']
    month = order_time.attrib['month']
    day = order_time.attrib['day']
    hour = order_time.attrib['hr']
    min = order_time.attrib['min']
    sec = order_time.attrib['sec']
    date_received = year +  month + day +  hour + min + sec
    due_date = order.find('due-date')
    due_date_time = due_date.find('time')
    yr = due_date_time.attrib['yr']
    month = due_date_time.attrib['month']
    day = due_date_time.attrib['day']
    s100rsd = "%s-%s-%s" %(yr, month, day)
    item_info = order.find('item-info')
    item_remarks = item_info.find('item-remarks')
    item_remark_list = item_remarks.findall('item-remark')
    item_remark_len = len(item_remark_list) - 1
    item_remark = item_remark_list[item_remark_len]
    remark = item_remark.find('remark')
    remark_text = remark.text


def main():
    config = ConfigParser.ConfigParser()
    config.readfp(open('part4b.ini'))
    server = config.get('main', 'Server')
    port = config.get('main', 'Port')
    port = int(port)
    schema = config.get('main', 'Schema') 
    table = config.get('main', 'Table')
    user = config.get('main', 'User')
    password = config.get('main', 'Password')
    source_path = config.get('main', 'filepath')

    db = MySQLdb.connect(server, user, password, schema, port)
    xml_list = os.listdir(source_path)
    for xml_file in xml_list:
        if xml_file.endswith('.xml'):
            parse_xml(source_path, xml_file)
            update_database(article_code, date_received, s100rsd, remark_text, db)

    db.close()

    print "This will close after 2 seconds . ."
    time.sleep(2)


if __name__ == '__main__':
    main()

In parse_xml function he don't want me to use global variables in it. How can I use those variables in my main without declaring it as globals?

Thanks for all your help.

2 Answers 2

4

return them from the function

eg

return article_code, date_received, s100rsd, remark_text

This is really returning a single tuple containing 4 items

you can extract them at the other end like this

article_code, date_received, s100rsd, remark_text = parse_xml(...)
6
  • 2
    Further to this ... it might be neater if you return an object with those values as attributes. Jul 13, 2012 at 6:33
  • Thanks for this. Sometimes my problem is so obvious, sorry for being newbie. Thanks again!
    – neo
    Jul 13, 2012 at 6:42
  • 1
    @MichaelAnderson, indeed. A namedtuple is a nice way to make such a lightweight object Jul 13, 2012 at 6:42
  • gnibbler, another question I want to ask. When I run my code in Aptana it runs okay. My code has no problem now. But when I double click my code at Python folder it didn't run at all. Why is that happening?
    – neo
    Jul 13, 2012 at 7:20
  • 1
    @jomskie19, you should ask that in a new question Jul 13, 2012 at 7:24
0

What you'd normally do is return a "data object", i.e. an object containing the relevant data:

class dto(object):
  def __init__(self, **kw):
    self.__dict__.update(kw)

def parse_xml(source_path, xml_file):
    data = dto(article_code = '1234',
               date_received = 'abc',
               s100rsd = '%s-%s-%s' % ('ab', 'cd', 'efgh'),
               remark_text = 'eh5jhe5')
    return data

data = parse_xml('../', 'abc.xml')

Then just use data.data_received as you'd expect.

Also note that your lines

os.listdir(source_path)
...
if xml_file.endswith('.xml'):

is real nice to replace with

import glob
xml_list = glob.glob(os.path.join(source_path, '*.xml'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.