Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Urlencode address data to prevent XML parsing error #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions usps/address.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from lxml import etree
from urllib.parse import quote


class Address(object):
QUOTE_SAFE_CHARS = " /"

def __init__(self, name, address_1, city, state, zipcode,
zipcode_ext='', company='', address_2='', phone=''):
Expand All @@ -15,32 +17,35 @@ def __init__(self, name, address_1, city, state, zipcode,
self.zipcode_ext = zipcode_ext
self.phone = phone

def _escape(self, string):
return quote(string, self.QUOTE_SAFE_CHARS)

def add_to_xml(self, root, prefix='To', validate=False):
if not validate:
name = etree.SubElement(root, prefix + 'Name')
name.text = self.name
name.text = self._escape(self.name)

company = etree.SubElement(root, prefix + 'Firm' + ('Name' if validate else ''))
company.text = self.company
company.text = self._escape(self.company)

address_1 = etree.SubElement(root, prefix + 'Address1')
address_1.text = self.address_1
address_1.text = self._escape(self.address_1)

address_2 = etree.SubElement(root, prefix + 'Address2')
address_2.text = self.address_2 or '-'
address_2.text = self._escape(self.address_2) or '-'

city = etree.SubElement(root, prefix + 'City')
city.text = self.city
city.text = self._escape(self.city)

state = etree.SubElement(root, prefix + 'State')
state.text = self.state
state.text = self._escape(self.state)

zipcode = etree.SubElement(root, prefix + 'Zip5')
zipcode.text = self.zipcode
zipcode.text = self._escape(self.zipcode)

zipcode_ext = etree.SubElement(root, prefix + 'Zip4')
zipcode_ext.text = self.zipcode_ext
zipcode_ext.text = self._escape(self.zipcode_ext)

if not validate:
phone = etree.SubElement(root, prefix + 'Phone')
phone.text = self.phone
phone.text = self._escape(self.phone)