Last active
December 12, 2015 22:02
-
-
Save SpaceVoyager/be60622f227dd3c5f5a8 to your computer and use it in GitHub Desktop.
functions for accessing puzzle scores web service
This file contains hidden or 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
| import requests | |
| import json | |
| import random | |
| import urllib | |
| END_POINT = 'http://192.168.1.8:5000/puzzlescores' | |
| def add_player(player_name): | |
| headers = {'Content-Type': 'application/json'} | |
| data = json.dumps({"name": player_name}) | |
| response = requests.post(END_POINT, data, headers=headers) | |
| return response.json() | |
| def get_sorted_players(): | |
| headers = {'Content-Type': 'application/json'} | |
| url = END_POINT + '?' + urllib.quote('where={"moves": {"$gt": 1}}&sort=moves,name', safe = '/=&') | |
| r = requests.get(url, headers=headers) | |
| response = r.json() | |
| results = [] | |
| for item in response['_items']: | |
| results.append({k:v for k,v in item.iteritems() if k in ['_updated', 'name', 'moves']}) | |
| return results | |
| # only update score if the new score is better | |
| def update_score(player_name, score): | |
| headers = {'Content-Type': 'application/json'} | |
| url = END_POINT + '?where=name=="' + urllib.quote(player_name) + '"' | |
| r = requests.get(url, headers=headers) | |
| response = r.json() | |
| if len(response.get('_items', [])) == 1: | |
| player_dict = response['_items'][0] | |
| if 'moves' not in player_dict or player_dict['moves'] > score: | |
| headers['If-Match'] = player_dict['_etag'] | |
| data = json.dumps({'moves': score}) | |
| r2 = requests.patch(END_POINT + '/' + player_dict['_id'], data, headers=headers) | |
| return r2.json() | |
| else: | |
| return {'_status': 'OK2', | |
| 'reason': 'score not updated because it is not better'} | |
| else: | |
| return {'_status': 'ERR', | |
| 'reason': 'player ' + player_name + ' not found'} | |
| # example usage | |
| print add_player('Snow Rabbit') | |
| print update_score('Snow Rabbit', 89) | |
| print get_sorted_players() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment