diff options
| author | yo mama <pepper@scannerjammer.com> | 2015-03-03 21:09:57 -0800 |
|---|---|---|
| committer | yo mama <pepper@scannerjammer.com> | 2015-03-03 21:09:57 -0800 |
| commit | b083ace52f49b7f3cd858ea5f1eea2b417a47a8a (patch) | |
| tree | b524897f2b8d936a9f07ea17c74df86381ad513d /lib/utils.py | |
| parent | 81dc62a3c958c3a0462a5d180f62395787d6ffe9 (diff) | |
added most of the api code
Diffstat (limited to 'lib/utils.py')
| -rw-r--r-- | lib/utils.py | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/lib/utils.py b/lib/utils.py new file mode 100644 index 0000000..0ad9aa3 --- /dev/null +++ b/lib/utils.py @@ -0,0 +1,49 @@ +import urllib +import urllib2 +import sys +import random +def post_request(url, params): + params = urllib.urlencode(params) + headers = { + "Content-type": "application/x-www-form-urlencoded", + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36", + "Accept": "text/plain" + } + try: + req = urllib2.Request(url, params, headers) + response = urllib2.urlopen(req) + return response.read() + except Exception as e: + sys.stderr.write(str(e)) + raise + +class Service: + def __init__(self): + self._required_keys = [] + self.url = "" + def new(self, params): + for k in self._required_keys: + if not k in params: + params[k] = ""; + self.current_params = params + return json.loads(post_request(self.url, self.current_params)) + +class Pb_Api_Params: + def _weighted_choice(self, param): + weights_total = sum(map(lambda x: x["weight"], param)) + choice = random.randint(0, weights_total) + position = 0 + for elem in param: + position += elem["weight"] + if position >= choice: + return elem["value"] + def _default_choice(self, param): + heaviest_idx = 0 + heaviest_weight = 0 + idx = 0 + for elem in param: + if elem["weight"] > heaviest_weight: + heaviest_weight = elem["weight"] + heaviest_idx = idx; + idx += 1 + return param[heaviest_idx]["value"] |
