コード例 #1
0
    def base_rate(self):
        rate = FedexRateServiceRequest(CONFIG_OBJ)

        rate.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
        rate.RequestedShipment.ServiceType = 'FEDEX_GROUND'
        rate.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

        rate.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'SC'
        rate.RequestedShipment.Shipper.Address.PostalCode = '29631'
        rate.RequestedShipment.Shipper.Address.CountryCode = 'US'

        rate.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'NC'
        rate.RequestedShipment.Recipient.Address.PostalCode = '27577'
        rate.RequestedShipment.Recipient.Address.CountryCode = 'US'

        rate.RequestedShipment.EdtRequestType = 'NONE'
        rate.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        package1_weight = rate.create_wsdl_object_of_type('Weight')
        package1_weight.Value = 1.0
        package1_weight.Units = "LB"
        package1 = rate.create_wsdl_object_of_type('RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.PhysicalPackaging = 'BOX'
        package1.GroupPackageCount = 1
        rate.add_package(package1)

        return rate
コード例 #2
0
ファイル: fedex_api.py プロジェクト: anndream/omniship
    def rate(self, packages, shipper, recipient, insurance='OFF', insurance_amount=0, delivery_confirmation=False,
             signature_confirmation=False):
        response = {'info': []}

        rate_request = FedexRateServiceRequest(self.config)
        rate_request = self._prepare_request(rate_request, shipper, recipient, packages)
        rate_request.RequestedShipment.ServiceType = None
        rate_request.RequestedShipment.EdtRequestType = 'NONE'
        rate_request.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'
        rate_request.RequestedShipment.ShippingChargesPayment.Payor.AccountNumber = self.config.account_number

        seen_quotes = []

        try:
            rate_request.send_request()

            for service in rate_request.response.RateReplyDetails:
                for detail in service.RatedShipmentDetails:
                    response['info'].append({
                        'service': service.ServiceType,
                        'package': service.PackagingType,
                        'delivery_day': '',
                        'cost': float(detail.ShipmentRateDetail.TotalNetFedExCharge.Amount)
                    })

        except Exception as e:
            raise FedExError(e)

        return response
コード例 #3
0
    def fedex_get_rates(self, picking, data):
        sys.path.insert(
            0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

        # Change these values to match your testing account/meter number.
        CONFIG_OBJ = FedexConfig(key=self.fedex_developer_key,
                                 password=self.fedex_developer_password,
                                 account_number=self.fedex_account_number,
                                 meter_number=self.fedex_meter_number,
                                 use_test_server=True if self.fedex_environment
                                 == 'test' else False)
        logging.basicConfig(stream=sys.stdout, level=logging.INFO)
        rr = FedexRateServiceRequest(CONFIG_OBJ,
                                     customer_transaction_id=picking.name)
        rr.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
        # rr.RequestedShipment.ServiceType = 'GROUND_HOME_DELIVERY'
        rr.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
        rr.RequestedShipment.RateRequestTypes = 'LIST'
        # Shipper's address
        rr.RequestedShipment.Shipper.Address.StreetLines = '15004 3rd Ave'
        rr.RequestedShipment.Shipper.Address.City = 'Highland Park'
        rr.RequestedShipment.Shipper.Address.PostalCode = '48203-3718'
        rr.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'MI'
        rr.RequestedShipment.Shipper.Address.CountryCode = 'US'

        # Recipient address
        rr.RequestedShipment.Recipient.Address.StreetLines = picking.partner_id.street
        rr.RequestedShipment.Recipient.Address.City = data['toCity']
        rr.RequestedShipment.Recipient.Address.PostalCode = data[
            'toPostalCode']
        rr.RequestedShipment.Recipient.Address.StateOrProvinceCode = data[
            'toState']
        rr.RequestedShipment.Recipient.Address.CountryCode = data['toCountry']
        rr.RequestedShipment.Recipient.Address.Residential = picking.residential

        # rr.RequestedShipment.EdtRequestType = 'NONE'
        rr.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        package1_weight = rr.create_wsdl_object_of_type('Weight')
        package1_weight.Value = int(data['weight']['value'])
        package1_weight.Units = "LB"

        package1_dimensions = rr.create_wsdl_object_of_type('Dimensions')
        package1_dimensions.Length = int(data['dimensions']['length'])
        package1_dimensions.Width = int(data['dimensions']['width'])
        package1_dimensions.Height = int(data['dimensions']['height'])
        package1_dimensions.Units = 'IN'

        package1 = rr.create_wsdl_object_of_type('RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.Dimensions = package1_dimensions
        package1.PhysicalPackaging = 'BOX'
        package1.GroupPackageCount = 1

        rr.add_package(package1)

        rr.send_request()
        return rr
コード例 #4
0
    def test_rate(self):
        rate = FedexRateServiceRequest(CONFIG_OBJ)

        rate.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
        rate.RequestedShipment.ServiceType = 'FEDEX_GROUND'
        rate.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

        rate.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'SC'
        rate.RequestedShipment.Shipper.Address.PostalCode = '29631'
        rate.RequestedShipment.Shipper.Address.CountryCode = 'US'

        rate.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'NC'
        rate.RequestedShipment.Recipient.Address.PostalCode = '27577'
        rate.RequestedShipment.Recipient.Address.CountryCode = 'US'

        rate.RequestedShipment.EdtRequestType = 'NONE'
        rate.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        package1_weight = rate.create_wsdl_object_of_type('Weight')
        package1_weight.Value = 1.0
        package1_weight.Units = "LB"
        package1 = rate.create_wsdl_object_of_type('RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.PhysicalPackaging = 'BOX'
        package1.GroupPackageCount = 1
        rate.add_package(package1)

        rate.send_request()

        assert rate.response.HighestSeverity == 'SUCCESS', rate.response.Notifications[
            0].Message
コード例 #5
0
 def __init__(self, to_country, postcode, weight, length, width, height, value, partner_name):
     fedex_config = FedexConfig(
         key=settings.FEDEX_ACCOUNT_KEY[partner_name],
         password=settings.FEDEX_ACCOUNT_PASSWORD[partner_name],
         account_number=settings.FEDEX_ACCOUNT_NUMBER[partner_name],
         meter_number=settings.FEDEX_METER_NUMBER[partner_name],
         freight_account_number=settings.FEDEX_FREIGHT_ACCOUNT_NUMBER[partner_name])
     self.rate_request = FedexRateServiceRequest(fedex_config)
     self.country_code = to_country.iso_3166_1_a2
     self.weight = float(weight)
     self.width = width
     self.length = length
     self.height = height
     self.value = value
     self.postcode = postcode
     self.partner_name = partner_name
コード例 #6
0
    def get_fedex_shipping_cost(self):
        """Returns the calculated shipping cost as sent by fedex
        :returns: The shipping cost
        """
        ProductUom = Pool().get('product.uom')

        fedex_credentials = self.carrier.get_fedex_credentials()

        if not all([
            self.fedex_drop_off_type, self.fedex_packaging_type,
            self.fedex_service_type
        ]):
            self.raise_user_error('fedex_settings_missing')

        rate_request = FedexRateServiceRequest(fedex_credentials)
        rate_request.RequestedShipment.DropoffType = self.fedex_drop_off_type.value
        rate_request.RequestedShipment.ServiceType = self.fedex_service_type.value
        rate_request.RequestedShipment.PackagingType = self.fedex_packaging_type.value
        rate_request.RequestedShipment.RateRequestTypes = "PREFERRED"
        rate_request.RequestedShipment.PreferredCurrency = self.currency.code

        # Shipper's address
        shipper_address = self._get_ship_from_address()
        rate_request.RequestedShipment.Shipper.Address.PostalCode = shipper_address.zip
        rate_request.RequestedShipment.Shipper.Address.CountryCode = shipper_address.country.code
        rate_request.RequestedShipment.Shipper.Address.Residential = False

        # Recipient address
        rate_request.RequestedShipment.Recipient.Address.PostalCode = self.shipment_address.zip
        rate_request.RequestedShipment.Recipient.Address.CountryCode = self.shipment_address.country.code

        # Include estimated duties and taxes in rate quote, can be ALL or NONE
        rate_request.RequestedShipment.EdtRequestType = 'NONE'

        # Who pays for the rate_request?
        # RECIPIENT, SENDER or THIRD_PARTY
        rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = \
            'SENDER'

        weight_uom, = ProductUom.search([('symbol', '=', 'lb')])

        package_weight = rate_request.create_wsdl_object_of_type('Weight')
        package_weight.Value = float("%.2f" % self._get_total_weight(weight_uom))
        package_weight.Units = "LB"
        package = rate_request.create_wsdl_object_of_type('RequestedPackageLineItem')
        package.Weight = package_weight
        # Can be other values this is probably the most common
        package.PhysicalPackaging = 'BOX'
        package.GroupPackageCount = 1

        rate_request.add_package(package)

        try:
            rate_request.send_request()
        except FedexError, error:
            self.raise_user_error("fedex_rates_error", error_args=(error, ))
コード例 #7
0
    def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):

        if shipping_addr:
            config = FedexConfig(key='YvEfQwGwT1TvCU2h',
                                 password='******',
                                 account_number='510087763',
                                 meter_number='118597992',
                                 use_test_server=True)
            ##rate request
            rate_request = FedexRateServiceRequest(config)
            rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
            rate_request.RequestedShipment.ServiceType = 'FEDEX_GROUND'
            rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
            rate_request.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'

            # Shipper's address
            rate_request.RequestedShipment.Shipper.Address.PostalCode = '29631'
            rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
            rate_request.RequestedShipment.Shipper.Address.Residential = False

            # Recipient address
            rate_request.RequestedShipment.Recipient.Address.PostalCode = shipping_addr.postcode
            rate_request.RequestedShipment.Recipient.Address.CountryCode = shipping_addr.country_id
            rate_request.RequestedShipment.EdtRequestType = 'NONE'
            rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

            package1_weight = rate_request.create_wsdl_object_of_type('Weight')
            # Weight, in LB.
            package1_weight.Value = 10.0
            package1_weight.Units = "LB"

            package1 = rate_request.create_wsdl_object_of_type(
                'RequestedPackageLineItem')
            package1.Weight = package1_weight
            package1.PhysicalPackaging = 'BOX'
            rate_request.add_package(package1)
            rate_request.send_request()
            for rate_detail in rate_request.response.RateReplyDetails[
                    0].RatedShipmentDetails:
                fedex_price = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
            ##set tax here (1.00)
            methods = [FixedPrice(D(fedex_price), D(fedex_price + 1.00))]
            return self.prime_methods(basket, methods)
        else:
            methods = [Free()]
            return self.prime_methods(basket, methods)
コード例 #8
0
    def rate_service(self, credentials, from_address_doc, to_address_doc, \
      from_country_doc, to_country_doc, transporter_doc):
        stop = 0
        from fedex.services.rate_service import FedexRateServiceRequest
        # Optional transaction_id
        customer_transaction_id = "*** RateService Request v18 using Python ***"
        rate_request = FedexRateServiceRequest(credentials, \
         customer_transaction_id=customer_transaction_id)
        rate_request.ReturnTransitAndCommit = True
        rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
        rate_request.RequestedShipment.ServiceType = transporter_doc.fedex_service_code
        rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
        rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'
        rate_request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.AccountNumber = \
            credentials.account_number
        rate_request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.PaymentType = self.duties_payment_by
        rate_request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Amount = self.amount
        rate_request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency = self.currency
        rate_request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.AccountNumber = \
         credentials.account_number if self.duties_payment_by == "SENDER" else ""

        self.set_shipper_info(rate_request, from_address_doc, credentials)
        self.set_recipient_info(rate_request, to_address_doc, credentials)
        #self.set_commodities_info(self, rate_request)
        self.set_commercial_invoice_info(rate_request)

        for row in self.shipment_package_details:
            package1 = self.set_package_weight(rate_request, row)
            package1.GroupPackageCount = 1
            rate_request.add_package(package1)
        rate_request.send_request()
        # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
        for service in rate_request.response.RateReplyDetails:
            for delivery in service:
                if delivery[0] == 'DeliveryTimestamp':
                    self.expected_delivery_date = delivery[1]
            for detail in service.RatedShipmentDetails:
                for surcharge in detail.ShipmentRateDetail.Surcharges:
                    if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
                        stop = 1
                        frappe.msgprint("{}: ODA rate_request charge {}".\
                         format(service.ServiceType, surcharge.Amount.Amount))

            for rate_detail in service.RatedShipmentDetails:
                self.shipment_cost = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
                self.shipment_cost_currency = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency
                self.save()
        if stop == 1 and allow_oda_shipment != 1:
            frappe.throw(
                'Out of Delivery Area, Booking of Shipment Not Allowed')
コード例 #9
0
    def fedex_set_shipping_price(self, order=None):
        recipient = order.partner_shipping_id if order.partner_shipping_id else order.partner_id
        currency_id = self.get_shipment_currency_id(order)
        currency_code = currency_id.name
        try:
            CurrencyCode = currency_id.name
            packaging_obj = self.env['product.packaging']
            result = 0.0
            currency_id = order.currency_id
            self.wk_validate_data(order=order)
            package_items = self.wk_get_order_package(order=order)
            items = self.wk_group_by('packaging_id', package_items)

            for order_packaging_id, wk_packaging_ids in items:

                packaging_id = packaging_obj.browse(order_packaging_id)
                rate_request = FedexRateServiceRequest(self.config_fedex())

                rate_request = self.fedex_preprocessing(rate_request,
                                                        packaging_id,
                                                        order=order)
                for wk_packaging_id in wk_packaging_ids:
                    weight = int(
                        round(
                            self._get_api_weight(
                                wk_packaging_id.get('weight'))))

                    package = self.get_fedex_package(
                        rate_request, weight, wk_packaging_id.get('length'),
                        wk_packaging_id.get('width'),
                        wk_packaging_id.get('height'), packaging_id)
                    rate_request.add_package(package)
                rate_request.send_request()
                amount = 0
                for service in rate_request.response.RateReplyDetails:
                    for rate_detail in service.RatedShipmentDetails:
                        CurrencyCode = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency
                        amount += float(rate_detail.ShipmentRateDetail.
                                        TotalNetFedExCharge.Amount)
                    result += amount
            return dict(currency_id=currency_id,
                        price=result,
                        currency=CurrencyCode,
                        success=True)

        except (FedexError, FedexFailure, SchemaValidationError) as f_err:
            _logger.warning("#1 FEDEX GET RATE ERROR-------%r---------------",
                            f_err.value)
            return dict(error_message=f_err.value, success=False)
        except Exception as e:
            _logger.warning("#2 FEDEX GET RATE ERROR-------%r---------------",
                            e)
            return dict(error_message=e, success=False)
コード例 #10
0
	def rate_service(self, credentials, from_address_doc, to_address_doc, \
			from_country_doc, to_country_doc, transporter_doc):
		stop = 0
		from fedex.services.rate_service import FedexRateServiceRequest
		# Optional transaction_id
		customer_transaction_id = "*** RateService Request v18 using Python ***"  
		rate_request = FedexRateServiceRequest(credentials, \
			customer_transaction_id=customer_transaction_id)
		rate_request.ReturnTransitAndCommit = True
		rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
		rate_request.RequestedShipment.ServiceType = transporter_doc.fedex_service_code
		rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
		rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'
		rate_request.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.AccountNumber = \
		    credentials.account_number
		rate_request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.PaymentType = self.duties_payment_by
		rate_request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Amount = self.amount
		rate_request.RequestedShipment.CustomsClearanceDetail.CustomsValue.Currency = self.currency
		rate_request.RequestedShipment.CustomsClearanceDetail.DutiesPayment.Payor.ResponsibleParty.AccountNumber = \
			credentials.account_number if self.duties_payment_by == "SENDER" else ""

		self.set_shipper_info(rate_request, from_address_doc, credentials)
		self.set_recipient_info(rate_request, to_address_doc, credentials)
		#self.set_commodities_info(self, rate_request)
		self.set_commercial_invoice_info(rate_request)

		for row in self.shipment_package_details:
			package1 = self.set_package_weight(rate_request, row)
			package1.GroupPackageCount = 1
			rate_request.add_package(package1)
		rate_request.send_request()
		# RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
		for service in rate_request.response.RateReplyDetails:
			for delivery in service:
				if delivery[0] == 'DeliveryTimestamp':
					self.expected_delivery_date = delivery[1]
			for detail in service.RatedShipmentDetails:
				for surcharge in detail.ShipmentRateDetail.Surcharges:
					if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
						stop = 1
						frappe.msgprint("{}: ODA rate_request charge {}".\
							format(service.ServiceType, surcharge.Amount.Amount))

			for rate_detail in service.RatedShipmentDetails:
				self.shipment_cost = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
				self.shipment_cost_currency = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency
				self.save()
		if stop == 1 and allow_oda_shipment != 1 :
			frappe.throw('Out of Delivery Area, Booking of Shipment Not Allowed')
コード例 #11
0
    def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):

            if shipping_addr:
                        config = FedexConfig(key='YvEfQwGwT1TvCU2h', password='******', account_number='510087763', meter_number='118597992', use_test_server=True)
                        ##rate request
                        rate_request = FedexRateServiceRequest(config)
                        rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
                        rate_request.RequestedShipment.ServiceType = 'FEDEX_GROUND'
                        rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
                        rate_request.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'

                        # Shipper's address
                        rate_request.RequestedShipment.Shipper.Address.PostalCode = '29631'
                        rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
                        rate_request.RequestedShipment.Shipper.Address.Residential = False

                        # Recipient address
                        rate_request.RequestedShipment.Recipient.Address.PostalCode = shipping_addr.postcode
                        rate_request.RequestedShipment.Recipient.Address.CountryCode = shipping_addr.country_id
                        rate_request.RequestedShipment.EdtRequestType = 'NONE'
                        rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

                        package1_weight = rate_request.create_wsdl_object_of_type('Weight')
                        # Weight, in LB.
                        package1_weight.Value = 10.0
                        package1_weight.Units = "LB"

                        package1 = rate_request.create_wsdl_object_of_type('RequestedPackageLineItem')
                        package1.Weight = package1_weight
                        package1.PhysicalPackaging = 'BOX'
                        rate_request.add_package(package1)
                        rate_request.send_request()
                        for rate_detail in rate_request.response.RateReplyDetails[0].RatedShipmentDetails:
                            fedex_price = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
                        ##set tax here (1.00)
                        methods = [FixedPrice(D(fedex_price), D(fedex_price+1.00))]
                        return self.prime_methods(basket, methods)
            else:
                        methods = [Free()]
                        return self.prime_methods(basket, methods)
コード例 #12
0
    def get_shipment_rate(self, doc):
        rate_request = FedexRateServiceRequest(self.config_obj)
        self.set_shipment_details(doc, rate_request)
        self.set_shipper_info(doc.company_address_name, rate_request)
        self.set_recipient_info(doc, rate_request)
        FedexController.set_commodities_info(doc, rate_request)
        rate_request.RequestedShipment.EdtRequestType = 'NONE'

        for row in doc.fedex_package_details:
            package1 = self.set_package_weight(rate_request, row, doc)
            package1.GroupPackageCount = 1
            rate_request.add_package(package1)

        self.set_commercial_invoice_info(rate_request, doc)
        rate_request.send_request()
        if rate_request.response.HighestSeverity not in [
                "SUCCESS", "NOTE", "WARNING"
        ]:
            self.show_notification(rate_request)
            frappe.throw(_("Error !!! Get shipment rate request failed."))
        return rate_request
コード例 #13
0
You will need to fill all of these, or risk seeing a SchemaValidationError
exception thrown by suds.

TIP: Near the bottom of the module, see how to check the if the destination
     is Out of Delivery Area (ODA).
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.rate_service import FedexRateServiceRequest

# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)

# This is the object that will be handling our tracking request.
# We're using the FedexConfig object from example_config.py in this dir.
rate_request = FedexRateServiceRequest(CONFIG_OBJ)

rate_request.RequestedShipment.ServiceType = 'FEDEX_FREIGHT_ECONOMY'

rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

rate_request.RequestedShipment.FreightShipmentDetail.TotalHandlingUnits = 1

rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightAccountNumber = CONFIG_OBJ.freight_account_number

rate_request.RequestedShipment.Shipper.Address.PostalCode = '72601'
rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
rate_request.RequestedShipment.Shipper.Address.City = 'Harrison'
rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'AR'
コード例 #14
0
ファイル: shipper.py プロジェクト: siddhant3030/Satchmo
    def calculate(self, cart, contact):
        # These imports are here to avoid circular import errors
        from satchmo_store.shop.models import Config
        from shipping.utils import product_or_parent
        shop_details = Config.objects.get_current()

        verbose = self.verbose_log

        if verbose:
            log.debug('Calculating fedex with type=%s', self.service_type_code)

        rate_request = FedexRateServiceRequest(self.CONFIG_OBJ)
        # This is very generalized, top-level information.
        # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
        rate_request.RequestedShipment.DropoffType = self.dropoff_type

        # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
        # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
        rate_request.RequestedShipment.ServiceType = self.service_type_code

        # What kind of package this will be shipped in.
        # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
        rate_request.RequestedShipment.PackagingType = self.packaging

        # No idea what this is.
        # INDIVIDUAL_PACKAGES, PACKAGE_GROUPS, PACKAGE_SUMMARY
        # rate_request.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'

        # Shipper's address
        rate_request.RequestedShipment.Shipper.Address.PostalCode = shop_details.postal_code
        rate_request.RequestedShipment.Shipper.Address.CountryCode = shop_details.country.iso2_code
        rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = shop_details.state

        rate_request.RequestedShipment.Shipper.Address.Residential = False

        # Recipient address
        rate_request.RequestedShipment.Recipient.Address.PostalCode = contact.shipping_address.postal_code
        rate_request.RequestedShipment.Recipient.Address.CountryCode = contact.shipping_address.country.iso2_code
        rate_request.RequestedShipment.Recipient.Address.StateOrProvinceCode = contact.shipping_address.state
        # This flag is optional. When turned on, it limits flexibility in options you can select
        #rate_request.RequestedShipment.Recipient.Address.Residential = True

        # Who pays for the rate_request?
        # RECIPIENT, SENDER or THIRD_PARTY
        rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        #EDT is used to determine which estimated taxes and duties are included in the response
        #For international shipments only
        rate_request.RequestedShipment.EdtRequestType = 'NONE'
        seq = 1
        # If we are using one, box we add up all the weights and ship in one box
        # Otherwise, we send multiple boxes
        default_weight_units = (self.default_weight_units or "").upper()
        assert default_weight_units in (
            'KG', 'LB'), "Valid default weight units are only KG or LB"
        if self.single_box:
            box_weight = 0.0
            for product in cart.get_shipment_list():
                item_weight = product_or_parent(product, 'weight') or 0.0
                converted_item_weight = (convert_weight(
                    float(item_weight),
                    product.smart_attr('weight_units') or default_weight_units,
                    default_weight_units))

                box_weight += max(converted_item_weight,
                                  float(self.default_weight))
            item = rate_request.create_wsdl_object_of_type(
                'RequestedPackageLineItem')
            item.SequenceNumber = seq
            item.Weight = rate_request.create_wsdl_object_of_type('Weight')
            item.Weight.Units = default_weight_units
            item.Weight.Value = box_weight
            item.PhysicalPackaging = 'BOX'
            rate_request.add_package(item)
        else:  # Send separate packages for each item
            for product in cart.get_shipment_list():
                item_weight = product_or_parent(product, 'weight')
                converted_item_weight = convert_weight(float(item_weight), product.smart_attr('weight_units') \
                        or default_weight_units, default_weight_units)
                item_weight = max(float(self.default_weight),
                                  float(self.default_weight))
                item = rate_request.create_wsdl_object_of_type(
                    'RequestedPackageLineItem')
                item.SequenceNumber = seq
                item.Weight.Units = default_weight_units
                item.Weight.Value = item_weight
                item.PhysicalPackaging = 'BOX'
                rate_request.add_package(item)
                seq += 1

        # If you'd like to see some documentation on the ship service WSDL, un-comment
        # this line. (Spammy).
        #print(rate_request.client)

        # Un-comment this to see your complete, ready-to-send request as it stands
        # before it is actually sent. This is useful for seeing what values you can
        # change.
        # print(rate_request.RequestedShipment)
        # Fires off the request, sets the 'response' attribute on the object.
        try:
            rate_request.send_request()
        except FedexBaseServiceException as e:
            # Expected Fedex exceptions with good messages are:
            # FedexFailure (for temporary server error), FedexError (for wrong request), SchemaValidationError
            log.info('******************* Error in shipping: %s' % str(e))
        except Exception as e:
            # Unexpected exceptions mostly need a traceback but also continue.
            log.info('******************* Error in shipping:\n%s',
                     traceback.format_exc(limit=15))

        # This will show the reply to your rate_request being sent. You can access the
        # attributes through the response attribute on the request object. This is
        # good to un-comment to see the variables returned by the FedEx reply.
        # print(rate_request.response)

        if rate_request.response:
            if rate_request.response.HighestSeverity in [
                    'SUCCESS', 'WARNING', 'NOTE'
            ]:
                # we're good
                log.debug('******************good shipping: %s' %
                          self.service_type_code)
                try:
                    self._expected_delivery = rate_request.response.RateReplyDetails[
                        0].TransitTime
                except AttributeError:  # TransitTime not included for everything
                    pass
                cost = 0
                for rate_detail in rate_request.response.RateReplyDetails[
                        0].RatedShipmentDetails:
                    cost = max(
                        cost, rate_detail.ShipmentRateDetail.
                        TotalNetFedExCharge.Amount)
                self._cost = Decimal(str(cost))
                self._valid = True
            else:
                log.debug('*******************bad shipping: %s' %
                          self.service_type_code)
                log.debug(rate_request.response.HighestSeverity)
                log.debug(rate_request.response.Notifications)
                self._valid = False
        else:
            self._valid = False
        self._calculated = True
コード例 #15
0
    def find_prices(self, package: Package) -> dict:
        """
        given a list or str of courrier types it will get the prices for each one
        :param package: Package detail
        :return: dict for each service to calculate with the price as value
        """
        service_prices = dict()

        # This is the object that will be handling our request.
        rate = FedexRateServiceRequest(CONFIG_OBJ)

        # This is very generalized, top-level information.
        # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
        rate.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

        # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
        # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
        # To receive rates for multiple ServiceTypes set to None.
        rate.RequestedShipment.ServiceType = None

        # What kind of package this will be shipped in.
        # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
        rate.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

        # Shipper's address
        rate.RequestedShipment.Shipper.Address.PostalCode = package.origin_zipcode
        rate.RequestedShipment.Shipper.Address.CountryCode = 'MX'

        # Recipient address
        rate.RequestedShipment.Recipient.Address.PostalCode = package.destiny_zipcode
        rate.RequestedShipment.Recipient.Address.CountryCode = 'MX'

        # This is needed to ensure an accurate rate quote with the response.
        # rate_request.RequestedShipment.Recipient.Address.Residential = True
        # include estimated duties and taxes in rate quote, can be ALL or NONE
        rate.RequestedShipment.EdtRequestType = 'NONE'

        # Who pays for the rate_request?
        # RECIPIENT, SENDER or THIRD_PARTY
        rate.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        # WSDL to manage the weight property
        package1_weight = rate.create_wsdl_object_of_type('Weight')
        # Weight, in KG.
        package1_weight.Value = package.weight
        package1_weight.Units = "KG"

        # WSDL to manage the dimensions properties
        # Optional but recommended if your package type is YOUR_PACKAGING.
        package1_dimensions = rate.create_wsdl_object_of_type('Dimensions')
        # Height, Width, and Length, in CM.
        package1_dimensions.Height = int(package.height)
        package1_dimensions.Width = int(package.width)
        package1_dimensions.Length = int(package.length)
        package1_dimensions.Units = "CM"

        package1 = rate.create_wsdl_object_of_type('RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.Dimensions = package1_dimensions

        # can be other values this is probably the most common
        package1.PhysicalPackaging = 'BOX'

        # Required, but according to FedEx docs:
        # "Used only with PACKAGE_GROUPS, as a count of packages within a
        # group of identical packages". In practice you can use this to get rates
        # for a shipment with multiple packages of an identical package size/weight
        # on rate request without creating multiple RequestedPackageLineItem elements.
        # You can OPTIONALLY specify a package group:
        # package1.GroupNumber = 0  # default is 0
        # The result will be found in RatedPackageDetail, with specified GroupNumber.
        package1.GroupPackageCount = 1

        # This adds the RequestedPackageLineItem WSDL object to the rate_request. It
        # increments the package count and total weight of the rate_request for you.
        rate.add_package(package1)

        # Fires off the request, sets the 'response' attribute on the object.

        # This will convert the response to a python dict object. To
        # make it easier to work with.
        # from fedex.tools.conversion import basic_sobject_to_dict
        # print(basic_sobject_to_dict(rate.response))

        # This will dump the response data dict to json.
        # from fedex.tools.conversion import sobject_to_json
        # result = sobject_to_json(rate.response)
        # print(result)

        # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
        try:
            rate.send_request()
            # print(rate.response)
            for service in rate.response.RateReplyDetails:
                for detail in service.RatedShipmentDetails:
                    for surcharge in detail.ShipmentRateDetail.Surcharges:
                        if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
                            pass

                for rate_detail in service.RatedShipmentDetails:
                    if service.ServiceType == 'STANDARD_OVERNIGHT':
                        service.ServiceType = 'FEDEX_STANDARD_OVERNIGHT'
                    service_prices[service.ServiceType] =\
                        rate_detail.ShipmentRateDetail.TotalNetChargeWithDutiesAndTaxes.Amount
        except AttributeError:
            raise CourrierErrors(
                "Servicio no disponible segun los datos proporcionados")
        except Exception as e:
            raise CourrierErrors(str(e))
            # raise CourrierErrors("FDX No respondió")

        return service_prices
コード例 #16
0
ファイル: partner.py プロジェクト: 3stratum/mmh
    def generate_fedex_shipping(self, cr, uid, ids, dropoff_type_fedex, service_type_fedex, packaging_type_fedex, package_detail_fedex, payment_type_fedex, physical_packaging_fedex, weight, shipper_postal_code,shipper_country_code,customer_postal_code,customer_country_code, sys_default=False,cust_default=False, error=True, context=None,fed_length=None,fed_width=None,fed_height=None,partner_id=None):
        if 'fedex_active' in context.keys() and context['fedex_active'] == False:
            return True
        res_partner_obj = self.pool.get('res.partner')
        shippingfedex_id = res_partner_obj.search(cr,uid,[('fedex_active','=',True),('id','=',partner_id)])
        if not shippingfedex_id:
            if error:                
                raise osv.except_osv(_('Warning !'),_('Active Fedex settings not defined!'))
            else:
                return False
        else:
            shippingfedex_id = shippingfedex_id[0]
        shippingfedex_ptr = res_partner_obj.browse(cr,uid,shippingfedex_id)
        account_no = shippingfedex_ptr.account_no
        key = shippingfedex_ptr.key
        password = shippingfedex_ptr.password
        meter_no = shippingfedex_ptr.meter_no
        is_test = shippingfedex_ptr.fedex_test
        CONFIG_OBJ = FedexConfig(key=key, password=password, account_number=account_no, meter_number=meter_no, use_test_server=is_test)
        rate_request = FedexRateServiceRequest(CONFIG_OBJ)
        # This is very generalized, top-level information.
        # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
        rate_request.RequestedShipment.DropoffType = dropoff_type_fedex
        # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
        # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
        rate_request.RequestedShipment.ServiceType = service_type_fedex
        # What kind of package this will be shipped in.
        # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
        rate_request.RequestedShipment.PackagingType = packaging_type_fedex
        # No idea what this is.
        # INDIVIDUAL_PACKAGES, PACKAGE_GROUPS, PACKAGE_SUMMARY
        rate_request.RequestedShipment.PackageDetail = package_detail_fedex
        rate_request.RequestedShipment.Shipper.Address.PostalCode = shipper_postal_code
        rate_request.RequestedShipment.Shipper.Address.CountryCode = shipper_country_code
        rate_request.RequestedShipment.Shipper.Address.Residential = False
        rate_request.RequestedShipment.Recipient.Address.PostalCode = customer_postal_code
        rate_request.RequestedShipment.Recipient.Address.CountryCode = customer_country_code
        # This is needed to ensure an accurate rate quote with the response.
        #rate_request.RequestedShipment.Recipient.Address.Residential = True
        #include estimated duties and taxes in rate quote, can be ALL or NONE
        rate_request.RequestedShipment.EdtRequestType = 'NONE'
        # Who pays for the rate_request?
        # RECIPIENT, SENDER or THIRD_PARTY
        rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = payment_type_fedex
        package1_weight = rate_request.create_wsdl_object_of_type('Weight')
        package1_weight.Value = weight
        package1_weight.Units = "LB"
        package1_dimensions=rate_request.create_wsdl_object_of_type('Dimensions')
        package1_dimensions.Length=int(fed_length)
        package1_dimensions.Width=int(fed_width)
        package1_dimensions.Height=int(fed_height)
        package1_dimensions.Units="IN"
        _logger.info("Package Dimensions %s", package1_dimensions)
        package1 = rate_request.create_wsdl_object_of_type('RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.Dimensions = package1_dimensions
        #can be other values this is probably the most common
        package1.PhysicalPackaging = physical_packaging_fedex
        # Un-comment this to see the other variables you may set on a package.
        # This adds the RequestedPackageLineItem WSDL object to the rate_request. It
        # increments the package count and total weight of the rate_request for you.
        rate_request.add_package(package1)
        # If you'd like to see some documentation on the ship service WSDL, un-comment
        # this line. (Spammy).
        # Un-comment this to see your complete, ready-to-send request as it stands
        # before it is actually sent. This is useful for seeing what values you can
        # change.
        # Fires off the request, sets the 'response' attribute on the object.
        try:
            rate_request.send_request()

        except Exception, e:
            if error:
#                raise Exception('%s' % (e))
                raise osv.except_osv(_('Warning !'),_('%s'%(e)))
            return False
コード例 #17
0
class FedexAPICalculator(object):
    def __init__(self, to_country, postcode, weight, length, width, height, value, partner_name):
        fedex_config = FedexConfig(
            key=settings.FEDEX_ACCOUNT_KEY[partner_name],
            password=settings.FEDEX_ACCOUNT_PASSWORD[partner_name],
            account_number=settings.FEDEX_ACCOUNT_NUMBER[partner_name],
            meter_number=settings.FEDEX_METER_NUMBER[partner_name],
            freight_account_number=settings.FEDEX_FREIGHT_ACCOUNT_NUMBER[partner_name])
        self.rate_request = FedexRateServiceRequest(fedex_config)
        self.country_code = to_country.iso_3166_1_a2
        self.weight = float(weight)
        self.width = width
        self.length = length
        self.height = height
        self.value = value
        self.postcode = postcode
        self.partner_name = partner_name

    def retrieveRates(self):
        shipping_options = []

        # This is very generalized, top-level information.
        # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
        self.rate_request.RequestedShipment.DropoffType = 'REQUEST_COURIER'
        #make sure we don't deliver on weekend
        now = datetime.datetime.now()
        if now.isoweekday() in range(1, 6):
            self.rate_request.RequestedShipment.ShipTimestamp = now
        else:
            self.rate_request.RequestedShipment.ShipTimestamp = now + datetime.timedelta(2)
        # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
        # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
        # To receive rates for multiple ServiceTypes set to None.
        self.rate_request.RequestedShipment.ServiceType = None

        # What kind of package this will be shipped in.
        # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
        self.rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

        # Shipper's address
        self.rate_request.RequestedShipment.Shipper.Address.PostalCode = '92705'
        self.rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'CA'
        self.rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
        self.rate_request.RequestedShipment.Shipper.Address.Residential = False

        # Recipient address
        self.rate_request.RequestedShipment.Recipient.Address.PostalCode = self.postcode
        self.rate_request.RequestedShipment.Recipient.Address.CountryCode = self.country_code
        # This is needed to ensure an accurate rate quote with the response.
        self.rate_request.RequestedShipment.Recipient.Address.Residential = True
        #include estimated duties and taxes in rate quote, can be ALL or NONE
        self.rate_request.RequestedShipment.EdtRequestType = 'ALL'

        # Who pays for the rate_request?
        # RECIPIENT, SENDER or THIRD_PARTY
        self.rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        package_weight = self.rate_request.create_wsdl_object_of_type('Weight')
        # Weight, in LB.
        package_weight.Value = self.weight
        package_weight.Units = "LB"

        package_dimensions = self.rate_request.create_wsdl_object_of_type('Dimensions')
        package_dimensions.Length = int(math.ceil(self.length))
        package_dimensions.Width = int(math.ceil(self.width))
        package_dimensions.Height = int(math.ceil(self.height))
        package_dimensions.Units.value = "IN"

        package = self.rate_request.create_wsdl_object_of_type('RequestedPackageLineItem')
        package.Weight = package_weight
        package.Dimensions = package_dimensions
        #declare contents value if its lower than $100 to get FedEx free insurance
        if self.value < 100:
            package.InsuredValue.Currency = 'USD'
            package.InsuredValue.Amount = self.value
        #package.Dimensions.Units = package1_dimensions_units
        #can be other values this is probably the most common
        package.PhysicalPackaging = 'BOX'
        # Required, but according to FedEx docs:
        # "Used only with PACKAGE_GROUPS, as a count of packages within a
        # group of identical packages". In practice you can use this to get rates
        # for a shipment with multiple packages of an identical package size/weight
        # on rate request without creating multiple RequestedPackageLineItem elements.
        # You can OPTIONALLY specify a package group:
        # package.GroupNumber = 0  # default is 0
        # The result will be found in RatedPackageDetail, with specified GroupNumber.
        package.GroupPackageCount = 1
        # Un-comment this to see the other variables you may set on a package.
        #print package

        # This adds the RequestedPackageLineItem WSDL object to the rate_request. It
        # increments the package count and total weight of the rate_request for you.
        self.rate_request.add_package(package)

        # If you'd like to see some documentation on the ship service WSDL, un-comment
        # this line. (Spammy).
        #print rate_request.client

        # Un-comment this to see your complete, ready-to-send request as it stands
        # before it is actually sent. This is useful for seeing what values you can
        # change.
        #print self.rate_request.RequestedShipment

        # Fires off the request, sets the 'response' attribute on the object.
        try:
            self.rate_request.send_request()
        except Exception:
            #log.critical("Fedex API error: %s, postal code: %s, country: %s" %
            #             (e, self.postcode, self.country_code))
            return shipping_options

        # This will show the reply to your rate_request being sent. You can access the
        # attributes throughgit status
        #  the response attribute on the request object. This is
        # good to un-comment to see the variables returned by the FedEx reply.
        #print rate_request.response

        # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
        try:
            for service in self.rate_request.response.RateReplyDetails:
                #rate includes postage + surcharges
                rate = service.RatedShipmentDetails[0].ShipmentRateDetail.TotalNetFedExCharge.Amount
                #print service.RatedShipmentDetails[0].ShipmentRateDetail
                kwargs = {
                    'ship_charge_excl_revenue': D(str(rate)),
                    'service_code': service.ServiceType,
                    'country_code': self.country_code,
                    'contents_value': self.value
                }
                try:
                    shipping_option = FedEx(**kwargs)
                except ShippingMethodDoesNotExist:
                    continue

                surcharges = []

                for detail in service.RatedShipmentDetails:
                    #print detail.ShipmentRateDetail.Surcharges
                    for surcharge in detail.ShipmentRateDetail.Surcharges:
                        if surcharge.Description == 'On call pickup':
                            #dirty patch that removes the on call pickup surcharge for GLOBAL and PREFERRED
                            #- they have a free daily pickup
                            #and their FedEx account returns this surcharge accidentally
                            if self.partner_name not in [settings.GLOBAL, settings.PREFERRED]:
                                surcharges.append((surcharge.Description, surcharge.Amount.Amount))
                        else:
                            surcharges.append((surcharge.Description, surcharge.Amount.Amount))

                    shipping_option.add_surcharges(surcharges)
                shipping_options.append(shipping_option)
        except AttributeError:
            pass
            #log.critical("Fedex API response error: no RateReplyDetails found,"
            #             " postal code: %s, country: %s" % (self.postcode, self.country_code))
        return shipping_options
コード例 #18
0
ファイル: rate_request.py プロジェクト: bartels/python-fedex
You will need to fill all of these, or risk seeing a SchemaValidationError 
exception thrown by suds.

TIP: Near the bottom of the module, see how to check the if the destination 
     is Out of Delivery Area (ODA).
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.rate_service import FedexRateServiceRequest

# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)

# This is the object that will be handling our tracking request.
# We're using the FedexConfig object from example_config.py in this dir.
rate_request = FedexRateServiceRequest(CONFIG_OBJ)

# This is very generalized, top-level information.
# REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

# See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
# STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
# To receive rates for multiple ServiceTypes set to None.
rate_request.RequestedShipment.ServiceType = 'FEDEX_GROUND'

# What kind of package this will be shipped in.
# FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

# No idea what this is.
コード例 #19
0
You will need to fill all of these, orrisk seeing a SchemaValidationError 
exception thrown by suds.

TIP: Near the bottom of the module, see how to check the if the destination 
     is Out of Delivery Area (ODA).
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.rate_service import FedexRateServiceRequest

# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)

# This is the object that will be handling our tracking request.
# We're using the FedexConfig object from example_config.py in this dir.
rate_request = FedexRateServiceRequest(CONFIG_OBJ)

# This is very generalized, top-level information.
# REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

# See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
# STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
rate_request.RequestedShipment.ServiceType = 'FEDEX_GROUND'

# What kind of package this will be shipped in.
# FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

# No idea what this is.
# INDIVIDUAL_PACKAGES, PACKAGE_GROUPS, PACKAGE_SUMMARY 
コード例 #20
0
def main():

    CONFIG_OBJ = FedexConfig(key='',
                             password='******',
                             account_number='',
                             meter_number='',
                             use_test_server=False)
    rate = FedexRateServiceRequest(CONFIG_OBJ)
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    customer_transaction_id = "*** RateService Request v18 using Python ***"  # Optional transaction_id

    # This is the object that will be handling our request which is utilized to retrieve rates
    rate_request = FedexRateServiceRequest(
        CONFIG_OBJ, customer_transaction_id=customer_transaction_id)
    #print(rate_request)

    # If you wish to have transit data returned with your request you
    # need to uncomment the following
    # rate_request.ReturnTransitAndCommit = True

    # This is very generalized, top-level information.
    # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
    rate_request.RequestedShipment.DropoffType = 'BUSINESS_SERVICE_CENTER'

    # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
    # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER
    # To receive rates for multiple ServiceTypes set to None.
    rate_request.RequestedShipment.ServiceType = 'PRIORITY_OVERNIGHT'

    # What kind of package this will be shipped in.
    # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
    rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

    # Shipper's address
    rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'TX'
    rate_request.RequestedShipment.Shipper.Address.PostalCode = '78728'
    rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = False

    # Recipient address
    rate_request.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'NC'
    rate_request.RequestedShipment.Recipient.Address.PostalCode = '27577'
    rate_request.RequestedShipment.Recipient.Address.CountryCode = 'US'
    # This is needed to ensure an accurate rate quote with the response.
    # rate_request.RequestedShipment.Recipient.Address.Residential = True
    # include estimated duties and taxes in rate quote, can be ALL or NONE
    rate_request.RequestedShipment.EdtRequestType = 'NONE'

    # Who pays for the rate_request?
    # RECIPIENT, SENDER or THIRD_PARTY
    rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

    # See https://www.fedex.com/us/developer/downloads/pdfs/2021/FedEx_WebServices_RateServices_WSDLGuide_v2021.pdf  for a full list.
    #Here are the common ones:
    # Weight, Dimensions

    package1_weight = rate_request.create_wsdl_object_of_type('Weight')
    # Weight, in LB. and limit is 150lbs for box shipments
    package1_weight.Value = 300
    package1_weight.Units = "LB"

    package1_dimensions = rate_request.create_wsdl_object_of_type('Dimensions')
    # Dimensions, in IN
    # Box size choices: 22X15X15, 24X18X18, 12X10X6, 18X12X12, 14X14X6
    package1_dimensions.Length = 48
    package1_dimensions.Width = 40
    package1_dimensions.Height = 55
    package1_dimensions.Units = "IN"

    package1 = rate_request.create_wsdl_object_of_type(
        'RequestedPackageLineItem')
    package1.Weight = package1_weight
    package1.Dimensions = package1_dimensions
    # can be other values this is probably the most common
    package1.PhysicalPackaging = 'BOX'
    # Required, but according to FedEx docs:
    # "Used only with PACKAGE_GROUPS, as a count of packages within a
    # group of identical packages". In practice you can use this to get rates
    # for a shipment with multiple packages of an identical package size/weight
    # on rate request without creating multiple RequestedPackageLineItem elements.
    # You can OPTIONALLY specify a package group:
    # package1.GroupNumber = 0  # default is 0
    # The result will be found in RatedPackageDetail, with specified GroupNumber.
    package1.GroupPackageCount = 1

    # Un-comment this to see the other variables you may set on a package.
    # print(package1)

    # This adds the RequestedPackageLineItem WSDL object to the rate_request. It
    # increments the package count and total weight of the rate_request for you.
    rate_request.add_package(package1)

    # If you'd like to see some documentation on the ship service WSDL, un-comment
    # this line. (Spammy).
    # print(rate_request.client)

    # Un-comment this to see your complete, ready-to-send request as it stands
    # before it is actually sent. This is useful for seeing what values you can
    # change.
    # print(rate_request.RequestedShipment)

    # Fires off the request, sets the 'response' attribute on the object.
    rate_request.send_request()

    # This will show the reply to your rate_request being sent. You can access the
    # attributes through the response attribute on the request object. This is
    # good to un-comment to see the variables returned by the FedEx reply.
    # print(rate_request.response)

    # This will convert the response to a python dict object. To
    # make it easier to work with.
    # from fedex.tools.conversion import basic_sobject_to_dict
    # print(basic_sobject_to_dict(rate_request.response))

    # This will dump the response data dict to json.
    # from fedex.tools.conversion import sobject_to_json
    # print(sobject_to_json(rate_request.response))

    # Here is the overall end result of the query.
    print("HighestSeverity: {}".format(rate_request.response.HighestSeverity))

    df = pd.DataFrame()
    df2 = pd.DataFrame()
    counter = 0

    # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
    for service in rate_request.response.RateReplyDetails:
        for detail in service.RatedShipmentDetails:
            for surcharge in detail.ShipmentRateDetail.Surcharges:
                if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
                    print("{}: ODA rate_request charge {}".format(
                        service.ServiceType, surcharge.Amount.Amount))

        #print fedex charge details (cost)
        for rate_detail in service.RatedShipmentDetails:
            #rate_detail=("{}: Net FedEx Charge {} {}".format(service.ServiceType,
            #                                          rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency,
            #                                       rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount))
            rate_detail = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
            if counter == 0:
                your_rate = float(rate_detail)
                print('\nYour rate \n', your_rate)
                df = df.append({'Your_rate': your_rate}, ignore_index=True)

            else:
                more_rates = float(rate_detail)
                print('\nMultiweight Rate \n', more_rates)
                df['Multiweight_rate'] = more_rates

            counter = +1

            my_dir = ''
            file_name = 'Fedex_Box_Quote.csv'
            fname = os.path.join(my_dir, file_name)
            df.to_csv(fname, index=False)
コード例 #21
0
You will need to fill all of these, or risk seeing a SchemaValidationError
exception thrown by suds.

TIP: Near the bottom of the module, see how to check the if the destination
     is Out of Delivery Area (ODA).
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.rate_service import FedexRateServiceRequest

# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)

# This is the object that will be handling our tracking request.
# We're using the FedexConfig object from example_config.py in this dir.
rate_request = FedexRateServiceRequest(CONFIG_OBJ)

rate_request.RequestedShipment.ServiceType = "FEDEX_FREIGHT_ECONOMY"

rate_request.RequestedShipment.DropoffType = "REGULAR_PICKUP"

rate_request.RequestedShipment.PackagingType = "YOUR_PACKAGING"

rate_request.RequestedShipment.FreightShipmentDetail.TotalHandlingUnits = 1

rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightAccountNumber = CONFIG_OBJ.freight_account_number


# Shipper
rate_request.RequestedShipment.Shipper.AccountNumber = CONFIG_OBJ.freight_account_number
rate_request.RequestedShipment.Shipper.Contact.PersonName = "Sender Name"
コード例 #22
0
def fedex(info):
    from fedex.config import FedexConfig
    from fedex.services.rate_service import FedexRateServiceRequest

    # Set API KEY
    CONFIG_OBJ = FedexConfig(key='vMdHkxHdMhV2oMlI',
                             password='******',
                             account_number='787098177',
                             meter_number='252470584')

    # Create request
    rate = FedexRateServiceRequest(CONFIG_OBJ)

    # service type
    rate.RequestedShipment.DropoffType = None
    rate.RequestedShipment.ServiceType = None
    rate.RequestedShipment.PackagingType = None

    # sender information
    rate.RequestedShipment.Shipper.Address.StateOrProvinceCode = info["ShipFrom"]["Address"]["StateProvinceCode"]
    rate.RequestedShipment.Shipper.Address.PostalCode = info["ShipFrom"]["Address"]["PostalCode"]
    rate.RequestedShipment.Shipper.Address.CountryCode = info["ShipFrom"]["Address"]["CountryCode"]

    # receiver information
    rate.RequestedShipment.Recipient.Address.StateOrProvinceCode = info["ShipTo"]["Address"]["StateProvinceCode"]
    rate.RequestedShipment.Recipient.Address.PostalCode = info["ShipTo"]["Address"]["PostalCode"]
    rate.RequestedShipment.Recipient.Address.CountryCode = info["ShipTo"]["Address"]["CountryCode"]

    # payer
    rate.RequestedShipment.EdtRequestType = 'NONE'
    rate.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

    # item information
    # Conversion unit of Dimension
    if info["Dimension units"] != "inches":  # CM to Inches
        info["Dimension units"] = "inches"
        info["Height"] = round(float(info["Height"]) * 0.393700787, 2)
        info["Length"] = round(float(info["Length"]) * 0.393700787, 2)
        info["Width"] = round(float(info["Width"]) * 0.393700787, 2)

    if float(info["Length"]) > 108:
        print('Package exceeds the maximum length constraints of 108 inches ')
        return []

    if float(info["Length"]) + 2 * float(info["Height"]) + 2 * float(info["Width"]) > 165:
        print('Package exceeds the maximum size total constraints of 165 inches ' \
              '(length + girth, where girth is 2 x width plus 2 x height)')
        return []

    package1_weight = rate.create_wsdl_object_of_type('Weight')
    # Conversion unit of Weight
    if info["Weight unit"] != "pounds":  # KG to pounds
        info["Weight unit"] = "pounds"
        info["Weight"] = round(float(info["Weight"]) * 2.20462262, 2)

    if float(info["Weight"]) > 150.00:
        print('The maximum per package weight is 150.00 pounds.')
        return []

    package1_weight.Value = round(float(info["Weight"]), 2)
    package1_weight.Units = "LB"
    package1 = rate.create_wsdl_object_of_type('RequestedPackageLineItem')
    package1.Weight = package1_weight
    package1.PhysicalPackaging = None
    package1.GroupPackageCount = 1
    rate.add_package(package1)

    # shipping time
    from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest
    avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ)
    avc_request.Origin.PostalCode = info["ShipFrom"]["Address"]["PostalCode"]
    avc_request.Origin.CountryCode = info["ShipFrom"]["Address"]["CountryCode"]
    avc_request.Destination.PostalCode = info["ShipTo"]["Address"]["PostalCode"]
    avc_request.Destination.CountryCode = info["ShipTo"]["Address"]["CountryCode"]

    # Try operation
    try:
        # send request
        rate.send_request()
        avc_request.send_request()
        # print(type(avc_request.response.Options))
        # for i in avc_request.response.Options:
        #     print(dict(i))
        # print(rate.response)
        rst = list()
        for service in rate.response.RateReplyDetails:
            for rate_detail in service.RatedShipmentDetails:
                # shipping time
                shipping_time = fedex_time(str(service.ServiceType), avc_request.response.Options)
                # service name
                try:
                    ser_name = str(service.ServiceType).replace('_', ' ')
                except:
                    ser_name = str(service.ServiceType)

                rst.append({"Company": "Fedex",
                            'Service': ser_name,
                            'Money': '$' + ' ' + str(rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount),
                            'Time': shipping_time})

        return rst

    except Exception as e:
        print('Fedex error information:' + str(e))
        return []
コード例 #23
0
def main():

    CONFIG_OBJ = FedexConfig(key='',
                             password='',
                             account_number='',
                             meter_number='',
                             freight_account_number='',
                             use_test_server=False)

    rate = FedexRateServiceRequest(CONFIG_OBJ)
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    customer_transaction_id = "*** RateService Request v18 using Python ***"  # Optional transaction_id

    # This is the object that will be handling our request which is utilized to retrieve rates
    rate_request = FedexRateServiceRequest(
        CONFIG_OBJ, customer_transaction_id=customer_transaction_id)

    rate_request.RequestedShipment.ServiceType = 'FEDEX_FREIGHT_ECONOMY'

    rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

    rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

    rate_request.RequestedShipment.FreightShipmentDetail.TotalHandlingUnits = 1

    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightAccountNumber = CONFIG_OBJ.freight_account_number

    # Shipper
    rate_request.RequestedShipment.Shipper.AccountNumber = CONFIG_OBJ.freight_account_number
    rate_request.RequestedShipment.Shipper.Contact.PersonName = 'Sender Name'
    rate_request.RequestedShipment.Shipper.Contact.CompanyName = 'Customer ABC'
    rate_request.RequestedShipment.Shipper.Address.StreetLines = [
        '123 Parker Drive'
    ]
    rate_request.RequestedShipment.Shipper.Address.City = 'Austin'
    rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'TX'
    rate_request.RequestedShipment.Shipper.Address.PostalCode = '78728'
    rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = False

    # Recipient
    rate_request.RequestedShipment.Recipient.Address.City = 'Harrison'
    rate_request.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'AR'
    rate_request.RequestedShipment.Recipient.Address.PostalCode = '72601'
    rate_request.RequestedShipment.Recipient.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = False

    # Payment
    payment = rate_request.create_wsdl_object_of_type('Payment')
    payment.PaymentType = "SENDER"
    payment.Payor.ResponsibleParty = rate_request.RequestedShipment.Shipper
    rate_request.RequestedShipment.ShippingChargesPayment = payment

    # include estimated duties and taxes in rate quote, can be ALL or NONE
    rate_request.RequestedShipment.EdtRequestType = 'NONE'

    # note: in order for this to work in test, you may need to use the
    # specially provided LTL addresses emailed to you when signing up.
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.PersonName = 'Sender Name'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.CompanyName = 'Customer ABC'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.StreetLines = [
        '111 Circle Drive'
    ]
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.City = 'Engelwood'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.StateOrProvinceCode = 'CO'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.PostalCode = '80111'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.CountryCode = 'US'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.Residential = False

    spec = rate_request.create_wsdl_object_of_type(
        'ShippingDocumentSpecification')

    spec.ShippingDocumentTypes = [spec.CertificateOfOrigin]

    rate_request.RequestedShipment.ShippingDocumentSpecification = spec

    role = rate_request.create_wsdl_object_of_type('FreightShipmentRoleType')
    rate_request.RequestedShipment.FreightShipmentDetail.Role = role.SHIPPER

    # Designates the terms of the "collect" payment for a Freight
    # Shipment. Can be NON_RECOURSE_SHIPPER_SIGNED or STANDARD
    rate_request.RequestedShipment.FreightShipmentDetail.CollectTermsType = 'STANDARD'

    package1_weight = rate_request.create_wsdl_object_of_type('Weight')
    package1_weight.Value = 300.0
    package1_weight.Units = "LB"

    rate_request.RequestedShipment.FreightShipmentDetail.PalletWeight = package1_weight

    package1_dimensions = rate_request.create_wsdl_object_of_type('Dimensions')
    package1_dimensions.Length = 48
    package1_dimensions.Width = 40
    package1_dimensions.Height = 40
    package1_dimensions.Units = "IN"

    #rate_request.RequestedShipment.FreightShipmentDetail= package1_dimensions
    #print (package1_dimensions)
    package1 = rate_request.create_wsdl_object_of_type(
        'FreightShipmentLineItem')
    print(package1)

    package1.Weight = package1_weight
    package1.Dimensions = package1_dimensions
    package1.Packaging = 'PALLET'
    package1.Description = 'Products'
    package1.FreightClass = 'CLASS_500'

    rate_request.RequestedShipment.FreightShipmentDetail.LineItems = package1
    print(package1)
    # If you'd like to see some documentation on the ship service WSDL, un-comment
    # this line. (Spammy).
    print(rate_request.client)

    # Un-comment this to see your complete, ready-to-send request as it stands
    # before it is actually sent. This is useful for seeing what values you can
    # change.
    # print(rate_request.RequestedShipment)

    # Fires off the request, sets the 'response' attribute on the object.
    rate_request.send_request()

    # This will show the reply to your rate_request being sent. You can access the
    # attributes through the response attribute on the request object. This is
    # good to un-comment to see the variables returned by the FedEx reply.
    # print(rate_request.response)

    # This will convert the response to a python dict object. To
    # make it easier to work with.
    # from fedex.tools.conversion import basic_sobject_to_dict
    # print(basic_sobject_to_dict(rate_request.response))

    # This will dump the response data dict to json.
    # from fedex.tools.conversion import sobject_to_json
    # print(sobject_to_json(rate_request.response))

    # Here is the overall end result of the query.
    print("HighestSeverity: {}".format(rate_request.response.HighestSeverity))

    # RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
    for service in rate_request.response.RateReplyDetails:
        for detail in service.RatedShipmentDetails:
            for surcharge in detail.ShipmentRateDetail.Surcharges:
                if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
                    print("{}: ODA rate_request charge {}".format(
                        service.ServiceType, surcharge.Amount.Amount))

        for rate_detail in service.RatedShipmentDetails:
            print("{}: Net FedEx Charge {} {}".format(
                service.ServiceType,
                rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency,
                rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount))
コード例 #24
0
TIP: Near the bottom of the module, see how to check the if the destination
     is Out of Delivery Area (ODA).
"""
import logging
import sys

from example_config import CONFIG_OBJ
from fedex.services.rate_service import FedexRateServiceRequest

# Un-comment to see the response from Fedex printed in stdout.
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

# This is the object that will be handling our request.
# We're using the FedexConfig object from example_config.py in this dir.
rate_request = FedexRateServiceRequest(CONFIG_OBJ)

rate_request.RequestedShipment.ServiceType = 'FEDEX_FREIGHT_ECONOMY'

rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

rate_request.RequestedShipment.FreightShipmentDetail.TotalHandlingUnits = 1

rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightAccountNumber = CONFIG_OBJ.freight_account_number

# Shipper
rate_request.RequestedShipment.Shipper.AccountNumber = CONFIG_OBJ.freight_account_number
rate_request.RequestedShipment.Shipper.Contact.PersonName = 'Sender Name'
rate_request.RequestedShipment.Shipper.Contact.CompanyName = 'Some Company'
コード例 #25
0
ファイル: views.py プロジェクト: rah1096/payment_and_shipping
def fedex_shipping(request):
    request_context = RequestContext(request)
    context = {'request': request}

    fedex_config = FedexConfig(key=settings.FEDEX_KEY,
                               password=settings.FEDEX_PASSWORD,
                               account_number=settings.FEDEX_ACCOUNT_NUMBER,
                               meter_number=settings.FEDEX_METER_NUMBER,
                               integrator_id=settings.FEDEX_INTEGRATOR_ID,
                               express_region_code=settings.FEDEX_EXPRESS_REGION_CODE,
                               use_test_server=True,
                               )

    fedex_ship_types = {}
    shipping_types = [
        (01, "PRIORITY_OVERNIGHT", "FedEx Priority Overnight"),
        (02, "PRIORITY_OVERNIGHT_SATURDAY_DELIVERY", "FedEx Priority Overnight Saturday Delivery"),
        (03, "FEDEX_2_DAY", "FedEx 2 Day"),
        (04, "FEDEX_2_DAY_SATURDAY_DELIVERY", "FedEx 2 Day Saturday Delivery"),
        (05, "STANDARD_OVERNIGHT", "FedEx Standard Overnight"),
        (06, "FIRST_OVERNIGHT", "FedEx First Overnight"),
        (07, "FIRST_OVERNIGHT_SATURDAY_DELIVERY", "FedEx First Overnight Saturday Delivery"),
        (08, "FEDEX_EXPRESS_SAVER", "FedEx Express Saver"),
        (09, "FEDEX_1_DAY_FREIGHT", "FedEx 1 Day Freight"),
        (10, "FEDEX_1_DAY_FREIGHT_SATURDAY_DELIVERY", "FedEx 1 Day Freight Saturday Delivery"),
        (11, "FEDEX_2_DAY_FREIGHT", "FedEx 2 Day Freight"),
        (12, "FEDEX_2_DAY_FREIGHT_SATURDAY_DELIVERY", "FedEx 2 Day Freight Saturday Delivery"),
        (13, "FEDEX_3_DAY_FREIGHT", "FedEx 3 Day Freight"),
        (14, "FEDEX_3_DAY_FREIGHT_SATURDAY_DELIVERY", "FedEx 3 Day Freight Saturday Delivery"),
        (15, "INTERNATIONAL_PRIORITY", "FedEx International Priority"),
        (16, "INTERNATIONAL_PRIORITY_SATURDAY_DELIVERY", "FedEx International Priority Saturday Delivery"),
        (17, "INTERNATIONAL_ECONOMY", "FedEx International Economy"),
        (18, "INTERNATIONAL_FIRST", "FedEx International First"),
        (19, "INTERNATIONAL_PRIORITY_FREIGHT", "FedEx International Priority Freight"),
        (20, "INTERNATIONAL_ECONOMY_FREIGHT", "FedEx International Economy Freight"),
        (21, "GROUND_HOME_DELIVERY", "FedEx Ground Home Delivery"),
        (22, "FEDEX_GROUND", "FedEx Ground"),
        (23, "INTERNATIONAL_GROUND", "FedEx International Ground"),
        (24, "SMART_POST", "FedEx SmartPost"),
        (25, "FEDEX_FREIGHT_PRIORITY", "FedEx Freight Priority"),
        (26, "FEDEX_FREIGHT_ECONOMY", "FedEx Freight Economy"),
    ]

    print shipping_types[1]

    for (x,y,z) in shipping_types:
        print "shipping # %s" % x
        print "shipping code: %s" % y
        print "shipping desc: %s" % z


    rate_request = FedexRateServiceRequest(fedex_config)

    rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
    rate_request.RequestedShipment.ServiceType = shipping_types[6][1]
    rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
    #rate_request.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'

    rate_request.RequestedShipment.Shipper.Address.PostalCode = '84604'
    rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = True

    rate_request.RequestedShipment.Recipient.Address.PostalCode = '84604'
    rate_request.RequestedShipment.Recipient.Address.CountryCode = 'US'
    rate_request.RequestedShipment.EdtRequestType = 'NONE'
    rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

    package1_weight = rate_request.create_wsdl_object_of_type('Weight')

    package1_weight.Value = 2
    package1_weight.Units = "LB"


    package1 = rate_request.create_wsdl_object_of_type('RequestedPackageLineItem')
    package1.Weight = package1_weight
    package1.GroupPackageCount = 1

    package1.PhysicalPackaging = 'BOX'
    rate_request.add_package(package1)

    rate_request.send_request()

    the_response = rate_request.response.RateReplyDetails

    context['response'] = the_response

    for service in rate_request.response.RateReplyDetails:
        for detail in service.RatedShipmentDetails:
            for surcharge in detail.ShipmentRateDetail.Surcharges:
                if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
                    print "%s: ODA rate_request charge %s" % (service.ServiceType, surcharge.Amount.Amount)
                    fedex = "%s: ODA rate_request charge %s" % (service.ServiceType, surcharge.Amount.Amount)
        for rate_detail in service.RatedShipmentDetails:
            print "%s: Net FedEx Charge %s %s" % (service.ServiceType, rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency,
            rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount)

        fedex_3_day = (rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount)

        context['response'] = fedex_3_day

    return render_to_response('fedex.html', context, context_instance=request_context)