forked from benqo/python-dhl
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathservice.py
More file actions
521 lines (465 loc) · 26.4 KB
/
Copy pathservice.py
File metadata and controls
521 lines (465 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
from suds.client import Client
from suds.wsse import Security, UsernameToken
from datetime import datetime
from dhl.resources.address import DHLPerson, DHLCompany, DHLRegistrationNumbers
from dhl.resources.package import DHLPackage
from dhl.resources.shipment import DHLShipment
from dhl.resources.response import DHLShipmentResponse, DHLPodResponse, \
DHLTrackingResponse, DHLTrackingEvent, DHLRateResponse
from dhl.resources.international_detail import DHLInternationalDetail
from suds.plugin import MessagePlugin
class LogPlugin(MessagePlugin):
def sending(self, context):
print(str(context.envelope))
def received(self, context):
print(str(context.reply))
class DHLService:
"""
Main class with static data and the main shipping methods.
"""
shipment_test_url = 'https://wsbexpress.dhl.com:443/sndpt/expressRateBook?WSDL'
shipment_url = 'https://wsbexpress.dhl.com:443/gbl/expressRateBook?WSDL'
pod_test_url = 'https://wsbexpress.dhl.com:443/sndpt/getePOD?WSDL'
pod_url = 'https://wsbexpress.dhl.com:443/gbl/getePOD?WSDL'
tracking_test_url = 'https://wsbexpress.dhl.com:443/sndpt/glDHLExpressTrack?WSDL'
tracking_url = 'https://wsbexpress.dhl.com:443/gbl/glDHLExpressTrack?WSDL'
def __init__(self, username, password, account_number, test_mode=False):
self.username = username
self.password = password
self.account_number = account_number
self.test_mode = test_mode
self.shipment_client = None
self.pod_client = None
self.tracking_client = None
def rate_request(self, shipment, message=None):
"""
Contacts to DHL Rate Request to obtain carrier rates for this shipment
:param shipment: DHLShipment object
:param message: optional message
:return: DHLResponse
"""
if not self.shipment_client:
url = self.shipment_test_url if self.test_mode else \
self.shipment_url
self.shipment_client = Client(url, faults=False, plugins=[LogPlugin()])
security = Security()
token = UsernameToken(self.username, self.password)
security.tokens.append(token)
self.shipment_client.set_options(wsse=security)
dhl_shipment = self._create_dhl_shipment_type2(self.shipment_client,
shipment)
result_code, reply = self.shipment_client.service.getRateRequest(
None, None, dhl_shipment)
if result_code == 500:
return DHLPodResponse(False, errors=[reply.detail.detailmessage])
elif result_code == 401:
return DHLPodResponse(False, errors=[('401', 'Unauthorized')])
for notif in reply.Notification:
if notif._code != '0':
print('[Code: ' + notif._code + ', '
'Message: ' + notif.Message + ']')
return DHLPodResponse(False, errors=[(notif._code,
notif.Message)])
return DHLRateResponse(True, reply.Service)
def send(self, shipment, message=None, auto=True):
"""
Creates the client, the DHL shipment and makes the DHL web request.
:param shipment: DHLShipment object
:param message: optional message
:return: DHLResponse
"""
if not self.shipment_client:
url = self.shipment_test_url if self.test_mode else self.shipment_url
self.shipment_client = Client(url, faults=False)
security = Security()
token = UsernameToken(self.username, self.password)
security.tokens.append(token)
self.shipment_client.set_options(wsse=security)
dhl_shipment = self._create_dhl_shipment(self.shipment_client, shipment, auto=auto)
result_code, reply = self.shipment_client.service.createShipmentRequest(message, None, None, dhl_shipment)
if result_code == 500:
return DHLPodResponse(False, errors=[reply.detail.detailmessage])
try:
identification_number = reply.ShipmentIdentificationNumber
package_results = reply.PackagesResult.PackageResult
tracking_numbers = [result.TrackingNumber for result in package_results]
try:
dispatch_number = reply.DispatchConfirmationNumber
except AttributeError:
dispatch_number = None
if reply.LabelImage[0].GraphicImage:
label_bytes = reply.LabelImage[0].GraphicImage
response = DHLShipmentResponse(
success=True,
tracking_numbers=tracking_numbers,
identification_number=identification_number,
label_bytes=label_bytes,
dispatch_number=dispatch_number
)
print('Successfully created DHL shipment!')
print(' Tracking numbers: ' + str(tracking_numbers))
print(' Identification number: ' + identification_number)
if dispatch_number:
response.dispatch_number = dispatch_number
print(' Dispatch number: ' + dispatch_number)
return response
else:
print(' No PDF label!')
response = DHLShipmentResponse(
success=False,
errors=['No PDF label.']
)
except AttributeError:
print('Unsuccessful DHL shipment request.')
response = DHLShipmentResponse(
success=False
)
try:
if reply.Notification:
print(' Notifications:')
errors = []
for notif in reply.Notification:
errors.append([notif._code, notif.Message])
print(' [Code: ' + notif._code + ', Message: ' + notif.Message + ']')
response.errors = errors
except AttributeError:
print(' No notifications.')
response.errors = ['No notifications.']
print()
return response
def proof_of_delivery(self, shipment_awb, detailed=True):
"""
Connects to DHL ePOD service, and returns the POD for the requested shipment.
:param shipment_awb: shipment waybill or identification number
:param detailed: if a detailed POD should be returned, else simple
:return: (True, pdf bytes) if successful else (False, [errors])
"""
if not self.pod_client:
url = self.pod_test_url if self.test_mode else self.pod_url
self.pod_client = Client(url, faults=False)
security = Security()
token = UsernameToken(self.username, self.password)
security.tokens.append(token)
self.pod_client.set_options(wsse=security)
msg = self._create_dhl_shipment_document(shipment_awb, detailed)
code, res = self.pod_client.service.ShipmentDocumentRetrieve(msg)
if code == 500:
return DHLPodResponse(False, errors=[res.detail.detailmessage])
try:
img = res.Bd.Shp[0].ShpInDoc[0].SDoc[0].Img[0]._Img
return DHLPodResponse(True, img)
except:
return DHLPodResponse(False, errors=[error.DatErrMsg.ErrMsgDtl._DtlDsc for error in res.DatTrErr])
def tracking(self, shipment_awb):
if not self.tracking_client:
url = self.tracking_test_url if self.test_mode else self.tracking_url
self.tracking_client = Client(url, faults=False)
security = Security()
token = UsernameToken(self.username, self.password)
security.tokens.append(token)
self.tracking_client.set_options(wsse=security)
tracking_request = self.tracking_client.factory.create('pubTrackingRequest')
tracking_request.TrackingRequest.Request.ServiceHeader.MessageTime = datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ')
tracking_request.TrackingRequest.Request.ServiceHeader.MessageReference = '123456789012345678901234567890'
tracking_request.TrackingRequest.AWBNumber.ArrayOfAWBNumberItem = shipment_awb
tracking_request.TrackingRequest.LevelOfDetails = 'ALL_CHECK_POINTS'
tracking_request.TrackingRequest.PiecesEnabled = 'B'
code, res = self.tracking_client.service.trackShipmentRequest(tracking_request)
if code == 500:
return DHLTrackingResponse(False, errors=[res.detail.detailmessage])
try:
return res.TrackingResponse.AWBInfo.ArrayOfAWBInfoItem[0].Pieces.PieceInfo.ArrayOfPieceInfoItem[0].PieceEvent[0]
except:
pass
try:
shipment_events = res.TrackingResponse.AWBInfo.ArrayOfAWBInfoItem[0].ShipmentInfo.ShipmentEvent.ArrayOfShipmentEventItem
dhl_shipment_events = []
for event in shipment_events:
tracking_event = DHLTrackingEvent(
code=event.ServiceEvent.EventCode,
location_code=event.ServiceArea.ServiceAreaCode,
location_description=event.ServiceArea.Description
)
dhl_shipment_events.append(tracking_event)
except:
pass
try:
pieces = res.TrackingResponse.AWBInfo.ArrayOfAWBInfoItem[0].Pieces.PieceInfo.ArrayOfPieceInfoItem
dhl_pieces_events = {}
for piece in pieces:
tracking_number = piece.PieceDetails.LicensePlate
dhl_pieces_events[tracking_number] = []
for event in piece.PieceEvent.ArrayOfPieceEventItem:
try:
dhl_pieces_events[tracking_number].append(
DHLTrackingEvent(
date=event.Date,
time=event.Time,
code=event.ServiceEvent.EventCode,
description=event.ServiceEvent.Description,
location_code=event.ServiceArea.ServiceAreaCode,
location_description=event.ServiceArea.Description
)
)
except:
pass
return DHLTrackingResponse(
success=True,
shipment_events=dhl_shipment_events,
pieces_events=dhl_pieces_events
)
except:
pass
########################################################################
# PRIVATE METHODS ######################################################
########################################################################
def _create_dhl_shipment_document(self, shipment_awb, detailed):
"""
Creates the DHL request for POD retrieve.
:param shipment_awb: shipment id
:param detailed: if detailed or simple pod
:return: message
"""
msg = self.pod_client.factory.create('shipmentDocumentRetrieveReq').MSG
msg.Hdr._Id = 'id'
msg.Hdr._Ver = '1.038'
msg.Hdr._Dtm = '2015-02-09T13:00:00'
msg.Hdr.Sndr._AppCd = 'DCG'
msg.Hdr.Sndr._AppNm = 'DCG'
msg.Bd.Shp = self.pod_client.factory.create('ns4:CdmShipment_Shipment')
msg.Bd.Shp._Id = str(shipment_awb)
msg.Bd.Shp.ShpInDoc = self.pod_client.factory.create('ns5:CdmShipment_CustomsDocuments_ShipmentDocumentation')
msg.Bd.Shp.ShpInDoc._DocTyCd = 'POD'
msg.Bd.Shp.ShpTr = self.pod_client.factory.create('ns4:CdmShipment_ShipmentTransaction')
msg.Bd.Shp.ShpTr.SCDtl = self.pod_client.factory.create('ns4:CdmShipment_ShipmentCustomerDetail')
if detailed:
msg.Bd.Shp.ShpTr.SCDtl._AccNo = self.account_number
msg.Bd.Shp.ShpTr.SCDtl._CRlTyCd = 'SP'
criterias = {
'IMG_CONTENT': 'epod-detail' if detailed else 'epod-summary',
'IMG_FORMAT': 'PDF',
'DOC_RND_REQ': 'true',
'EXT_REQ': 'true',
'DUPL_HANDL': 'CORE_WB_NO',
'SORT_BY': '$INGEST_DATE,D',
'LANGUAGE': 'en'
}
msg.Bd.GenrcRq = self.pod_client.factory.create('ns2:CdmGenericRequest_GenericRequest')
for key, value in criterias.items():
criteria = self.pod_client.factory.create('ns2:CdmGenericRequest_GenericRequestCriteria')
criteria._TyCd = key
criteria._Val = value
msg.Bd.GenrcRq.GenrcRqCritr += (criteria,)
return msg
def _create_dhl_shipment(self, client, shipment, auto=True):
"""
Creates a soap DHL shipment from the DHLShipment and the soap client.
:param client: soap client
:param shipment: DHLShipment object
:return: soap dhl shipment
"""
shipment.automatically_set_predictable_fields(auto=auto)
dhl_shipment = client.factory.create('ns4:docTypeRef_RequestedShipmentType')
dhl_shipment.ShipmentInfo.Currency = shipment.currency
dhl_shipment.ShipmentInfo.UnitOfMeasurement = shipment.unit
dhl_shipment.ShipmentInfo.LabelType = shipment.label_type
dhl_shipment.ShipmentInfo.LabelTemplate = shipment.label_template
dhl_shipment.ShipmentInfo.Account = self.account_number
dhl_shipment.ShipmentInfo.ServiceType = shipment.service_type
dhl_shipment.ShipmentInfo.QRCodeImageFormat = 'PNG'
dhl_shipment.ShipmentInfo.RequestAdditionalInformation = 'N'
dhl_shipment.ShipmentInfo.RequestEstimatedDeliveryDate = 'N'
dhl_shipment.ShipmentInfo.EstimatedDeliveryDateType = 'QDDC'
dhl_shipment.ShipmentInfo.RequestPickupDetails = 'N'
dhl_shipment.ShipmentInfo.LabelOptions.CustomerLogo.LogoImage = shipment.logo_image
dhl_shipment.ShipmentInfo.LabelOptions.CustomerLogo.LogoImageFormat = shipment.logo_image_format
dhl_shipment.ShipmentInfo.LabelOptions.RequestWaybillDocument = shipment.request_waybill_document
dhl_shipment.ShipmentInfo.LabelOptions.DHLCustomsInvoiceType = shipment.customs_invoice_type
dhl_shipment.ShipmentInfo.LabelOptions.RequestBarcodeInfo = 'N'
dhl_shipment.ShipmentInfo.LabelOptions.RequestDHLCustomsInvoice = shipment.customs_dhl_invoice
#dhl_shipment.ShipmentInfo.PackagesCount = str(len(shipment.packages))
dhl_shipment.PaymentInfo = shipment.payment_info_paperless
list_service = client.factory.create('Services')
for service in shipment.service:
special_service_element = client.factory.create('Service')
special_service_element.ServiceType = service
list_service.Service.append(special_service_element)
dhl_shipment.ShipmentInfo.SpecialServices = list_service
dhl_shipment.InternationalDetail.Commodities.Description = shipment.customs_description
dhl_shipment.InternationalDetail.Commodities.CustomsValue = shipment.customs_value
dhl_shipment.InternationalDetail.Content = shipment.customs_content
if shipment.international_detail:
dhl_shipment.InternationalDetail.ExportDeclaration.InvoiceNumber = shipment.international_detail.invoice_reference_number
dhl_shipment.InternationalDetail.ExportDeclaration.InvoiceDate = shipment.international_detail.invoice_date
dhl_shipment.InternationalDetail.ExportDeclaration.ShipmentPurpose = 'COMMERCIAL'
dhl_shipment.InternationalDetail.ExportDeclaration.DocumentFunction = 'EXPORT'
dhl_shipment.InternationalDetail.ExportDeclaration.InvoiceReferences.\
InvoiceReference.InvoiceReferenceType = shipment.international_detail.invoice_reference_type
dhl_shipment.InternationalDetail.ExportDeclaration.InvoiceReferences.\
InvoiceReference.InvoiceReferenceNumber = shipment.international_detail.invoice_reference_number
if shipment.international_detail.other_charge:
dhl_shipment.InternationalDetail.ExportDeclaration.OtherCharges.OtherCharge = ()
for other_charge_vals in shipment.international_detail.other_charge:
other_charge = client.factory.create('OtherCharge')
other_charge.Caption = other_charge_vals.charge_caption
other_charge.ChargeValue = other_charge_vals.charge_value
other_charge.ChargeType = other_charge_vals.charge_type
dhl_shipment.InternationalDetail.ExportDeclaration.OtherCharges.OtherCharge += (other_charge,)
dhl_shipment.InternationalDetail.ExportDeclaration.ExportLineItems.ExportLineItem = ()
line_count = 0
for export_line in shipment.international_detail.export_line_items:
line_count += 1
export_line_item = client.factory.create('ExportLineItemType')
export_line_item.ItemNumber = line_count
export_line_item.CommodityCode = export_line.commodity_code
export_line_item.Quantity = export_line.quantity
export_line_item.QuantityUnitOfMeasurement = export_line.quantity_unit
export_line_item.ItemDescription = export_line.item_description
export_line_item.UnitPrice = export_line.unit_price
export_line_item.NetWeight = export_line.net_weight
export_line_item.GrossWeight = export_line.gross_weight
export_line_item.ExportReasonType = 'PERMANENT'
export_line_item.ManufacturingCountryCode = export_line.manufactoring_country_code
dhl_shipment.InternationalDetail.ExportDeclaration.ExportLineItems.ExportLineItem += (export_line_item,)
dhl_shipment.ShipmentInfo.DropOffType = shipment.drop_off_type
dhl_shipment.ShipTimestamp = shipment.get_dhl_formatted_shipment_time()
dhl_shipment.PickupLocationCloseTime = shipment.get_dhl_formatted_pickup_time()
dhl_shipment.SpecialPickupInstruction = shipment.special_pickup_instructions
dhl_shipment.ShipmentInfo.PaperlessTradeEnabled = shipment.paperles_sistem
dhl_shipment.ShipmentInfo.PaperlessTradeImage = shipment.invoice_paperles
dhl_shipment.Ship.Shipper.Contact.PersonName = shipment.sender.person_name
dhl_shipment.Ship.Shipper.Contact.CompanyName = shipment.sender.company_name
dhl_shipment.Ship.Shipper.Contact.PhoneNumber = shipment.sender.phone
if shipment.sender.email:
dhl_shipment.Ship.Shipper.Contact.EmailAddress = shipment.sender.email
dhl_shipment.Ship.Shipper.Address.StreetLines = shipment.sender.street_lines
dhl_shipment.Ship.Shipper.Address.StreetLines2 = shipment.sender.street_lines2
dhl_shipment.Ship.Shipper.Address.StreetLines3 = shipment.sender.street_lines3
dhl_shipment.Ship.Shipper.Address.City = shipment.sender.city
dhl_shipment.Ship.Shipper.Address.PostalCode = shipment.sender.postal_code
dhl_shipment.Ship.Shipper.Address.CountryCode = shipment.sender.country_code
dhl_shipment.Ship.Shipper.RegistrationNumbers = client.factory.create('ns4:docTypeRef_RegistrationNumbers')
registration_numbers = client.factory.create('ns4:docTypeRef_RegistrationNumber')
if shipment.registration_numbers:
registration_numbers.Number = shipment.registration_numbers.vat
registration_numbers.NumberTypeCode = shipment.registration_numbers.type_code
registration_numbers.NumberIssuerCountryCode = shipment.registration_numbers.country_code_vat
dhl_shipment.Ship.Shipper.RegistrationNumbers.RegistrationNumber += (registration_numbers,)
dhl_shipment.Ship.Recipient.Contact.PersonName = shipment.receiver.person_name
dhl_shipment.Ship.Recipient.Contact.CompanyName = shipment.receiver.company_name
dhl_shipment.Ship.Recipient.Contact.PhoneNumber = shipment.receiver.phone
if shipment.receiver.email:
dhl_shipment.Ship.Recipient.Contact.EmailAddress = shipment.receiver.email
dhl_shipment.Ship.Recipient.Address.StreetLines = shipment.receiver.street_lines
dhl_shipment.Ship.Recipient.Address.StreetLines2 = shipment.receiver.street_lines2
dhl_shipment.Ship.Recipient.Address.StreetLines3 = shipment.receiver.street_lines3
dhl_shipment.Ship.Recipient.Address.City = shipment.receiver.city
dhl_shipment.Ship.Recipient.Address.PostalCode = shipment.receiver.postal_code
dhl_shipment.Ship.Recipient.Address.CountryCode = shipment.receiver.country_code
# Exporter
dhl_shipment.Ship.Exporter.Contact.PersonName = shipment.exporter_personal_name
dhl_shipment.Ship.Exporter.Contact.CompanyName = shipment.exporter_company_name
dhl_shipment.Ship.Exporter.Contact.PhoneNumber = shipment.exporter_phone_number
dhl_shipment.Ship.Exporter.Contact.EmailAddress = shipment.exporter_email
dhl_shipment.Ship.Exporter.Address.StreetLines = shipment.exporter_street
dhl_shipment.Ship.Exporter.Address.StreetLines2 = shipment.exporter_street2
dhl_shipment.Ship.Exporter.Address.City = shipment.exporter_city
dhl_shipment.Ship.Exporter.Address.PostalCode = shipment.exporter_postal_code
dhl_shipment.Ship.Exporter.Address.CountryCode = shipment.exporter_country_code
dhl_shipment.Ship.Exporter.RegistrationNumbers.RegistrationNumber = client.factory.create('docTypeRef_RegistrationNumber')
dhl_shipment.Ship.Exporter.RegistrationNumbers.RegistrationNumber.Number = shipment.exporter_number
dhl_shipment.Ship.Exporter.RegistrationNumbers.RegistrationNumber.NumberTypeCode = shipment.exporter_type_code
dhl_shipment.Ship.Exporter.RegistrationNumbers.RegistrationNumber.NumberIssuerCountryCode = shipment.exporter_number_issuer_country_code
# Buyer
dhl_shipment.Ship.Buyer.Contact.PersonName = shipment.buyer_personal_name
dhl_shipment.Ship.Buyer.Contact.CompanyName = shipment.buyer_company_name
dhl_shipment.Ship.Buyer.Contact.PhoneNumber = shipment.buyer_phone_number
dhl_shipment.Ship.Buyer.Contact.EmailAddress = shipment.buyer_email
dhl_shipment.Ship.Buyer.Address.StreetLines = shipment.buyer_street
dhl_shipment.Ship.Buyer.Address.StreetLines2 = shipment.buyer_street2
dhl_shipment.Ship.Buyer.Address.City = shipment.buyer_city
dhl_shipment.Ship.Buyer.Address.PostalCode = shipment.buyer_postal_code
dhl_shipment.Ship.Buyer.Address.CountryCode = shipment.buyer_country_code
dhl_shipment.Ship.Buyer.RegistrationNumbers.RegistrationNumber = client.factory.create('docTypeRef_RegistrationNumber')
dhl_shipment.Ship.Buyer.RegistrationNumbers.RegistrationNumber.Number = shipment.buyer_number
dhl_shipment.Ship.Buyer.RegistrationNumbers.RegistrationNumber.NumberTypeCode = shipment.buyer_type_code
dhl_shipment.Ship.Buyer.RegistrationNumbers.RegistrationNumber.NumberIssuerCountryCode = shipment.buyer_number_issuer_country_code
counter = 1
dhl_shipment.Packages.RequestedPackages = ()
for package in shipment.packages:
dhl_package = client.factory.create('ns4:docTypeRef_RequestedPackagesType')
dhl_package._number = str(counter)
dhl_package.Weight = str(package.weight)
dhl_package.Dimensions.Length = str(package.length)
dhl_package.Dimensions.Width = str(package.width)
dhl_package.Dimensions.Height = str(package.height)
dhl_package.PieceIdentificationNumber = shipment.reference_code
dhl_package.CustomerReferences = shipment.reference_code
dhl_package.PackageContentDescription = str(package.description)
dhl_shipment.Packages.RequestedPackages += (dhl_package,)
counter += 1
return dhl_shipment
def _create_dhl_shipment_type2(self, client, shipment):
"""
Creates a SOAP DHL Shipment type2. This Shipment type is used for
rate requests
:param client: soap client
:param shipment: DHLShipment object
:return: soap dhl shipment
"""
dhl_shipment = client.factory.create(
'ns2:docTypeRef_RequestedShipmentType2')
dhl_shipment.Content = shipment.customs_content
dhl_shipment.NextBusinessDay = 'Y'
dhl_shipment.UnitOfMeasurement = shipment.unit
dhl_shipment.DropOffType.value = shipment.drop_off_type
dhl_shipment.Account = self.account_number
dhl_shipment.PaymentInfo = shipment.payment_info
dhl_shipment.ShipTimestamp = shipment.get_dhl_formatted_shipment_time()
dhl_shipment.Ship.Shipper.StreetLines =\
shipment.sender.street_lines
dhl_shipment.Ship.Shipper.StreetLines2 =\
shipment.sender.street_lines2
dhl_shipment.Ship.Shipper.StreetLines3 =\
shipment.sender.street_lines3
dhl_shipment.Ship.Shipper.City =\
shipment.sender.city
dhl_shipment.Ship.Shipper.PostalCode =\
shipment.sender.postal_code
dhl_shipment.Ship.Shipper.CountryCode =\
shipment.sender.country_code
dhl_shipment.Ship.Recipient.StreetLines =\
shipment.receiver.street_lines
dhl_shipment.Ship.Recipient.StreetLines2 =\
shipment.receiver.street_lines2
dhl_shipment.Ship.Recipient.StreetLines3 =\
shipment.receiver.street_lines3
dhl_shipment.Ship.Recipient.City =\
shipment.receiver.city
dhl_shipment.Ship.Recipient.PostalCode =\
shipment.receiver.postal_code
dhl_shipment.Ship.Recipient.CountryCode =\
shipment.receiver.country_code
counter = 1
dhl_shipment.Packages.RequestedPackages = ()
for package in shipment.packages:
dhl_package = client.factory.create(
'ns2:docTypeRef_RequestedPackagesType2')
dhl_package._number = str(counter)
dhl_package.Weight.Value = str(package.weight)
dhl_package.Dimensions.Length = str(package.length)
dhl_package.Dimensions.Width = str(package.width)
dhl_package.Dimensions.Height = str(package.height)
dhl_shipment.Packages.RequestedPackages += (dhl_package,)
counter += 1
# Delete empty elements
to_delete = []
for key in dhl_shipment.__keylist__:
try:
if not dhl_shipment[key].value:
to_delete.append(key)
except:
if not dhl_shipment[key]:
to_delete.append(key)
[delattr(dhl_shipment, key) for key in to_delete]
return dhl_shipment