Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Ordrin Python API

Reorganized namespace
  • Loading branch information...
commit 37db390d4ba2f98ac7c59b722f97d79f92f770e9 1 parent 724f5f6
@zainalam zainalam authored
View
BIN  Ordrin/.DS_Store
Binary file not shown
View
78 Ordrin/__init__.py
@@ -0,0 +1,78 @@
+"""
+Ordr.in Python Library Alpha
+http://www.ordr.in
+
+Copyright 2011
+Last updated: July 11
+"""
+
+import datetime, re, r, u, o, api
+
+class Address():
+ def __init__(self, street, city, zip, street2="", state="", phone="", nick=""):
+ self.nick = nick
+ self.street = "+".join(street.split(" "))
+ self.street2 = "+".join(street2.split(" "))
+ self.city = "+".join(city.split(" "))
+ self.zip = zip
+ self.state = state
+ self.phone = phone
+ def validate(self, element="all"):
+ if element == "zip" and not re.match("(^\d{5}$)|(^\d{5}-\d{4}$)", self.zip):
+ api._errs.append("Address object - validation - zip code (invalid)")
+ elif element == "phone" and self.phone and not re.match("(^\(?(\d{3})\)?[- .]?(\d{3})[- .]?(\d{4})$)", self.phone):
+ api._errs.append("Address object - validation - phone number (invalid)")
+ elif element == "city" and not re.match("[A-Za-z.-]", self.city):
+ api._errs.append("Address object - validation - city (invalid, only letters/spaces allowed)")
+ elif element == "state" and self.state and not re.match("^([A-Za-z]){2}$", self.state):
+ api._errs.append("Address object - validation - state (invalid, only letters allowed and must be passed as two-letter abbreviation)")
+ else:
+ if not re.match("(^\d{5}$)|(^\d{5}-\d{4}$)", self.zip):
+ api._errs.append("Address object - validation - zip code (invalid)")
+ if self.phone and not re.match("^\(?(\d{3})\)?[- .]?(\d{3})[- .]?(\d{4})$", self.phone):
+ api._errs.append("Address object - validation - phone number (invalid)")
+ if not re.match("[A-Za-z.-]", self.city):
+ api._errs.append("Address object - validation - city (invalid, only letters/spaces allowed)")
+ if self.state and not re.match("^([A-Za-z]){2}$", self.state):
+ api._errs.append("Address object - validation - state (invalid, only letters allowed and must be passed as two-letter abbreviation)")
+ def _convertForRAPI(self):
+ return self.zip + "/" + self.city + "/" + self.street;
+
+class dTime(datetime.datetime):
+ def asap(self):
+ self.asap = 1
+ def _strAPI(self, element):
+ if element == "month":
+ if self.month < 10:
+ return "0" + str(self.month)
+ else:
+ return self.month
+ if element == "day":
+ if self.day < 10:
+ return "0" + str(self.day)
+ else:
+ return self.day
+ if element == "hour":
+ if self.hour < 10:
+ return "0" + str(self.hour)
+ else:
+ return self.hour
+ if element == "minute":
+ if self.minute < 10:
+ return "0" + str(self.minute)
+ else:
+ return self.minute
+ def convertForRAPI(self):
+ if self.asap == 1:
+ return "ASAP"
+ else:
+ return self.month + "-" + self.day + "+" + self.hour + ":" + self.minute
+
+class Money():
+ def __init__(self, amount):
+ if not int(amount):
+ api._errs.append(("validation", "money must be numerical"))
+ else:
+ self.amount = amount
+ def _convertForRAPI(self):
+ return str(self.amount * 100)
View
76 Ordrin/api.py
@@ -0,0 +1,76 @@
+import urllib2, re, json, hashlib
+
+_key = ""
+_url = ""
+
+_currEmail = ""
+_currPass = ""
+
+_errs = []
+
+_checkNums = "^\s*\d+\s*$"
+_checkEmail = "^[a-zA-Z0-9._%-+]+@[a-zA-Z0-9._%-]+.[a-zA-Z]{2,6}$"
+_checkCC = "^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$"
+
+def initialize(key, url):
+ global _key, _url
+ _key = key
+ _url = url
+
+def setCurrAcct(currEmail, currPass):
+ global _currEmail, _currPass
+ if not re.match(_checkEmail, currEmail):
+ _errs.append("api.setCurrAcct - validation - email (invalid)")
+ _currEmail = currEmail
+ _currPass = hashlib.sha256(currPass).hexdigest()
+
+def _request(type, *args):
+ dataParams = []
+ urlParams = []
+
+ if not _key:
+ _errs.append(("initialization", "must initialize with developer key for API"))
+ elif not _url:
+ _errs.append(("initialization", "must initialize with site at which API is running"))
+
+ # seperate arguments into appropriate lists
+ for i in args:
+ i = str(i)
+ if re.search("=", i):
+ dataParams.append(i)
+ print i
+ else:
+ if i == "uN": # this is to prevent the header for the user API going out with the makeAcct function
+ iN = "u"
+ urlParams.append(iN)
+ else:
+ urlParams.append(i)
+
+ append = "/" + "/".join(urlParams)
+ print "URL: " + _url
+ print "append: " + append
+
+ opener = urllib2.build_opener(urllib2.HTTPHandler)
+ request = urllib2.Request(_url + append, "&".join(dataParams))
+ request.add_header('X-NAAMA-CLIENT-AUTHENTICATION', 'id="' + _key + '", version="1"')
+ request.add_header("Content-Type", "application/x-www-form-urlencoded");
+
+ if args[0] == "u":
+ if not _currEmail or not _currPass:
+ _errs.append(("user API", "valid email and password required to access user API"))
+ print "Hash is being created."
+ hash = hashlib.sha256(_currPass + _currEmail + append).hexdigest()
+ print "hash: " + hash
+ request.add_header("X-NAAMA-AUTHENTICATION", 'username="' + _currEmail + '", response="' + hash + '", version="1"')
+ print "header looks like: " + 'username="' + _currEmail + '", response="' + hash + '", version="1"'
+
+ if _errs:
+ print _errs
+ return _errs
+ raise
+
+ request.get_method = lambda: type
+ call = opener.open(request)
+
+ print call.read()
+ # return json.loads(response.read())
View
22 Ordrin/o.py
@@ -0,0 +1,22 @@
+import api, re
+
+def submit(restaurantID, tray, tip, dTime, em, first_name, last_name, addr, card_name, card_number, card_cvc, card_expiry, ccAddr):
+ addr.validate()
+ ccAddr.validate()
+ if not re.match(api._checkNums, restaurantID):
+ api._errs.append("o.submit - validation - restaurant ID (invalid, must be numerical)")
+ if not re.match(api._checkCC, card_number):
+ api._errs.append("o.submit - validation - credit card number (invalid)")
+ if not re.match(api._checkNums, card_cvc):
+ api._errs.append("o.submit - validation - credit card security code (invalid, must be numerical)")
+ if not re.match(api._checkEmail, em):
+ api._errs.append("o.submit - validation - email (invalid)")
+
+ if (dTime.asap):
+ date = "ASAP"
+ time = ""
+ else:
+ date = dTime._strAPI("month") + "-" + dTime._strAPI("day")
+ time = dTime._strAPI("hour") + ":" + dTime._strAPI("minute")
+
+ api._request("POST", "o", restaurantID, "tray=" + tray, "tip=" + tip._convertForRAPI(), "delivery_date=" + date, "delivery_time=" + time, "first_name=" + first_name, "last_name=" + last_name, "addr=" + addr._street, "city=" + addr.city, "state=" + addr.state, "zip=" + addr.zip, "phone=" + addr.phone, "em=" + em, "card_name=" + card_name, "card_number=" + card_number, "card_cvc=" + card_cvc, "card_expiry=" + card_expiry, "card_bill_addr=" + ccAddr._street, "card_bill_addr2=" + ccAddr._street2, "card_bill_city=" + ccAddr.city, "card_bill_state=" + ccAddr.state, "card_bill_zip=" + ccAddr.zip, "type=RES");
View
22 Ordrin/r.py
@@ -0,0 +1,22 @@
+import api, re
+
+def deliveryList(dT, addr):
+ addr.validate()
+
+ api._request("GET", "dl", dT._convertForRAPI(), addr.zip, addr.city, addr.street)
+def deliveryCheck(rID, dT, addr):
+ if not re.match(api._checkNums, rID):
+ api._errs.append("r.deliveryCheck - validation - restaurant ID (invalid, must be numerical)")
+ addr.validate()
+
+ api._request("GET", "dc", rID, dT._convertForRAPI(), addr.zip, addr.city, addr.street)
+def deliveryFee(rID, subtotal, tip, dT, addr):
+ if not re.match(api._checkNums, rID):
+ api._errs.append("r.deliveryCheck - validation - restaurant ID (invalid, must be numerical)")
+ addr.validate()
+
+ api._request("GET", "fee", rID, subtotal._convertForRAPI(), tip._convertForRAPI(), dT._convertForRAPI(), addr.zip, addr.city, addr.street)
+def details(rID):
+ if not re.match(api._checkNums, rID):
+ api._errs.append("r.deliveryCheck - validation - restaurant ID (invalid, must be numerical)")
+ api._request("GET", "rd", rID)
View
35 Ordrin/u.py
@@ -0,0 +1,35 @@
+import api, hashlib
+
+def makeAcct(email, password, firstName, lastName):
+ # password before submission must be SHA256-encoded; to be fixed with API update
+ # api._request("POST", "u", email, "password=" + hashlib.sha256(password).hexdigest(), "first_name=" + firstName, "last_name=" + lastName)
+ api._request("POST", "uN", email, "password=" + password, "first_name=" + firstName, "last_name=" + lastName)
+def getAcct(): # get details on current user
+ api._request("GET", "u", api._currEmail)
+def getAddress(addrNick=""):
+ if addrNick:
+ api._request("GET", "u", api._currEmail, "addrs", addrNick)
+ else:
+ api._request("GET", "u", api._currEmail, "addrs")
+def updateAddress(addr): # Address must be passed using API's built-in Address object
+ addr.validate()
+ api._request("PUT", "u", api._currEmail, "addrs", addr.nick, "addr=" + addr.street, "addr2=" + addr.street2, "city=" + addr.city, "state=" + addr.state, "zip=" + addr.zip, "phone=" + addr.phone)
+def deleteAddress(addrNick):
+ api._request("DELETE", "u", api._currEmail, "addrs", addrNick)
+def getCard(cardNick=""):
+ if cardNick:
+ api._request("GET", "u", api._currEmail, "ccs", cardNick)
+ else:
+ api._request("GET", "u", api._currEmail, "ccs")
+def updateCard(cardNick, name, number, cvc, expiryMonth, expiryYear, addr):
+ addr.validate()
+ api._request("PUT", "u", api._currEmail, "ccs", cardNick, "name=" + name, "number=" + number, "cvc=" + cvc, "expiry_month=" + expiryMonth, "expiry_year=" + expiryYear, "bill_addr=" + addr.street, "bill_addr2=" + addr.street2, "bill_city=" + addr.city, "bill_state=" + addr.state, "bill_zip=" + addr.zip)
+def deleteCard(cardNick):
+ api._request("DELETE", "u", api._currEmail, "ccs", cardNick)
+def orderHistory(orderID=""): # if orderID left blank, all previous orders returned: ID returns specific details of order
+ if orderID:
+ api._request("GET", "u", api._currEmail, "order", orderID)
+ else:
+ api._request("GET", "u", api._currEmail, "orders")
+def updatePassword(password):
+ api._request("PUT", "u", api._currEmail, "password", "password=" + hashlib.sha256(password).hexdigest())
Please sign in to comment.
Something went wrong with that request. Please try again.