Last active
December 11, 2015 18:08
-
-
Save czpython/4639258 to your computer and use it in GitHub Desktop.
Script to test out the Python MWS API.
It takes all orders created on 01/10/2013 and outputs them to a csv file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Sample script for mws api. | |
""" | |
import csv | |
from collections import OrderedDict | |
from mws import mws | |
# A module containing the API credentials | |
from config import * | |
################################# CONSTANTS ####################################### | |
# An ordered dictionary mapping a csv header to the response key containing it's value. | |
# Note that the "__" means it's nested. | |
# Doing the headers this way makes it pretty easy to add more columns to the file. | |
CSV_HEADERS = OrderedDict() | |
CSV_HEADERS['Name'] = 'ShippingAddress__Name' | |
CSV_HEADERS['Order ID'] = 'AmazonOrderId' | |
CSV_HEADERS['PurchaseDate'] = 'PurchaseDate' | |
CSV_HEADERS['AddressLine1'] = 'ShippingAddress__AddressLine1' | |
CSV_HEADERS['AddressLine2'] = 'ShippingAddress__AddressLine2' | |
CSV_HEADERS['AddressLine3'] = 'ShippingAddress__AddressLine3' | |
CSV_HEADERS['City'] = 'ShippingAddress__City' | |
CSV_HEADERS['StateOrRegion'] = 'ShippingAddress__StateOrRegion' | |
CSV_HEADERS['PostalCode'] = 'ShippingAddress__PostalCode' | |
# A value to be placed under a csv header when no value has been found. | |
EMPTY_VALUE = '' | |
# Pretty self explanatory | |
FILENAME = '/home/paulo/orders.tsv' | |
def generate_orders_csv(orders, filename, headers): | |
""" | |
orders -> list of dictionaries | |
filename -> string or path to the where the file will be created/named. | |
headers -> ordered dictionary mapping csv headers to the respective key from the response. | |
Main function whose task is to generate a csv file | |
from orders with name "filename" and "headers". | |
""" | |
with open(filename, 'w') as new_csv_file: | |
# The csv module is pretty good at reading/writing csvs give it a try :). | |
csv_writer = csv.DictWriter( | |
new_csv_file, | |
fieldnames=headers.keys(), | |
delimiter='\t', | |
) | |
csv_writer.writeheader() | |
for order in orders: | |
if order: | |
row = populate_row_from_object(order, headers) | |
csv_writer.writerow(row) | |
def query_object(obj, query): | |
""" | |
This takes an object and a query string. | |
It travels down the object as if it were a tree using query. | |
""" | |
parsed = query.split('__') | |
while len(parsed) >= 1: | |
try: | |
obj = getattr(obj, parsed[0]) | |
except KeyError, e: | |
return EMPTY_VALUE | |
parsed = parsed[1:] | |
return obj | |
def populate_row_from_object(obj, headers): | |
row = {} | |
for header in headers: | |
row[header] = query_object(obj, headers[header]) | |
return row | |
## ORDERS API ################################################################# | |
# First we get our info from the orders API. It does not provide information | |
# about cancelled orders. | |
def orders(orderstatus=None): | |
"""Retreive orders, fulfilled by seller. | |
The created_before and created_after dates are set through config.py as | |
DAYS_BACK, because we'll always be fetching today's orders. | |
order_status (str) -- may be one of: None, Pending, Unshipped, | |
PartiallyShipped, Shipped, InvoiceUnconfirmed, | |
Canceled, Unfulfillable. None is any of the | |
previous. | |
Might need TFMShipmentStatus? | |
https://images-na.ssl-images-amazon.com/images/G/01/mwsportal/doc/en_US/orders/MWSOrdersApiReference._V401547137_.pdf | |
""" | |
if orderstatus is None: | |
# In the MWS API (the one I wrote) the order status is an iterable. | |
# In this case I provide this list as a default. | |
orderstatus = ['PartiallyShipped','Unshipped', ] | |
## BUILD REQUEST ---------------------------------------------------------- | |
amazon = mws.Orders(*CREDENTIALS) | |
params = { | |
'marketplaceids': [MARKETPLACE_ID], | |
'created_after': '2013-01-10', | |
'orderstatus': orderstatus, | |
} | |
orders = amazon.list_orders(**params).parsed.Orders.Order | |
generate_orders_csv(orders, filename=FILENAME, headers=CSV_HEADERS) | |
orders() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment