def load_schedule(): # http://flask.pocoo.org/docs/0.11/patterns/fileuploads/ # https://gist.github.com/DazWorrall/1779861 schedule_file = request.files.get('schedule') if not schedule_file: raise InvalidUsage('Schedule file not provided') filename = secure_filename(schedule_file.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) schedule_file.save(filepath) with open(filepath) as schedule_upload: try: schedule_json = json.load(schedule_upload) except Exception as ex: raise InvalidUsage('Invalid JSON: {}'.format(ex)) for idx, schedule_item in enumerate(schedule_json): show = Show(**schedule_item) missing_columns = show.missing_columns() if not missing_columns: db.session.add(show) else: raise InvalidUsage('Missing `{}` for schedule index {}'.format( missing_columns, idx)) db.session.commit() return 'OK'
def song(song_id): # check playlist_mode playlist_mode = session.get('playlist_mode') if playlist_mode != 'edit': raise InvalidUsage("Can't edit songs in readonly mode") # check song exists try: song = db.session.query(Song).filter_by(id=song_id).one() except NoResultFound as ex: raise InvalidUsage('No song found for id: {}'.format(song_id)) # parse json request try: song_data = request.get_json() except Exception as ex: raise InvalidUsage('Invalid JSON') for key, value in song_data.items(): if hasattr(song, key): setattr(song, key, value) else: raise InvalidUsage("Song has no attribute: {}".format(key)) db.session.add(song) db.session.commit() return 'OK'
def delete_song(display_id): # check playlist_mode playlist_mode = session.get('playlist_mode') if playlist_mode != 'edit': raise InvalidUsage("Can't delete songs in readonly mode") try: request_json = request.get_json() song_id = request_json.get('song_id') except Exception as ex: raise InvalidUsage('Invalid JSON') # check song exists try: song = db.session.query(Song).filter_by(id=song_id).one() except NoResultFound as ex: raise InvalidUsage('No song found for id: {}'.format(song_id)) # check playlist exists try: playlist = db.session.query(Playlist).filter_by( display_id=display_id).one() except NoResultFound as ex: raise InvalidUsage('No playlist found for id: {}'.format(display_id)) # check song in playlist if song not in playlist.songs: raise InvalidUsage("Song id {} not in playlist id {}".format( song.id, playlist.display_id)) db.session.delete(song) db.session.commit() return 'OK'
def addSample(): content = request.get_json() device_uuid = content.get('device_uuid') sensor_type = content.get('sensor_type') sensor_value = content.get('sensor_value') sensor_reading_time = content.get('sensor_reading_time') if device_uuid is None: raise InvalidUsage("Requires device_uuid") if sensor_type is None: raise InvalidUsage("Requires sensor_type") if sensor_value is None: raise InvalidUsage("Requires sensor_value") if sensor_reading_time is None: raise InvalidUsage("Requires sensor_reading_time") try: sample = SensorSample(device_uuid=device_uuid, sensor_type=sensor_type, sensor_value=sensor_value, sensor_reading_time=sensor_reading_time) db.session.add(sample) db.session.flush() db.session.commit() except AssertionError as exception_message: raise InvalidUsage(str(exception_message)) return jsonify(sample.serialize())
def broadcast(): try: token = request.headers['X-Auth-Token'] except KeyError: raise InvalidUsage('Invalid auth', status_code=401) (res, login) = auth(token) if not res: raise InvalidUsage('Invalid auth', status_code=401) try: data = json.loads(request.data.decode('utf-8')) ip = data['ip'] port = data['port'] op = data['op'] except (json.decoder.JSONDecodeError, KeyError): raise InvalidUsage('Invalid body', status_code=400) if op == 1: online[login] = (ip, port) elif op == 0: online.pop(login) index = 0 for i in range(len(users)): if users[i].login == login: index = i del users[index] pprint(online) res = jsonify(success=True) return res
def transfer(): content = request.json if 'player_name_dst' not in content: raise InvalidUsage("Player destination not given", status_code=400) if 'coins' not in content: raise InvalidUsage("Coins not given", status_code=400) with lock: game.transfer(get_player(), content['player_name_dst'], int(content['coins'])) return "", 200
def transfer_card(): content = request.json if 'player_name_dst' not in content: raise InvalidUsage("Player destination not given", status_code=400) if 'card_id' not in content: raise InvalidUsage("Card id not given", status_code=400) with lock: game.transfer_card(get_player(), content['player_name_dst'], content['card_id']) return "", 200
def get_player() -> Optional[Player]: if 'playerId' not in session: raise InvalidUsage("No player id in session", status_code=401) player = game.get_player(session['playerId']) if not player: raise InvalidUsage("Game doesn't have the player id that was sent", status_code=401) return player
def start_game(): content = request.json if 'cardNames' not in content: raise InvalidUsage("Cards names not given", status_code=400) if not is_list_of_strings(content['cardNames']): raise InvalidUsage("Cards names is not list of strings", status_code=400) if 'playerToStart' not in content: raise InvalidUsage("Player to start not given", status_code=400) with lock: game.start(content['cardNames'], content['playerToStart']) return "", 204
def validated_params_winddirection(request): """ Returns extracted, processed, and validated required request parameters. This version is desiged for winddirection queries. """ if 'height' in request.args: height_str = request.args['height'] if len(height_str) > 0 and height_str[-1] == "m": try: height = float(height_str.rstrip("m")) except ValueError: raise InvalidUsage(("Height provided is malformed. " "Please use the notation: 'XXm' " "(where 'm' is for meters and XX is a " "positive number; it doesn't need to be " "an integer).")) if height < 0: raise InvalidUsage("Height should be a positive number.") else: raise InvalidUsage(("Height provided is malformed. " "Please use the notation: 'XXm' " "(where 'm' is for meters and XX is a " "positive number; it doesn't need to be " "an integer).")) if 'lat' in request.args: try: lat = float(request.args['lat']) except ValueError: raise InvalidUsage(("Lat (latitude) provided is invalid." "Needs to be a number.")) else: raise InvalidUsage("Lat (latitude) is not provided.") if 'lon' in request.args: try: lon = float(request.args['lon']) except ValueError: raise InvalidUsage(("Lon (longitude) provided is invalid." "Needs to be a number.")) else: raise InvalidUsage("Lon (longitude) is not provided.") if 'start_date' in request.args: start_date = validated_dt(request.args['start_date']) else: raise InvalidUsage(("Error: No start_date field provided. " "Please specify start_date.")) if 'stop_date' in request.args: stop_date = validated_dt(request.args['stop_date']) else: raise InvalidUsage(("Error: No stop_date field provided. " "Please specify stop_date.")) return height, lat, lon, start_date, stop_date
def getSamplesForID(): device_uuid = request.args.get('device_uuid') sensor_type = request.args.get('sensor_type') start_time = request.args.get('start_time') end_time = request.args.get('end_time') bundle_query = db.session.query(SensorSample) if device_uuid is not None: bundle_query = bundle_query.filter( SensorSample.device_uuid == device_uuid) if sensor_type is not None: bundle_query = bundle_query.filter( SensorSample.sensor_type == sensor_type) if start_time is not None and end_time is not None: bundle_query = bundle_query.filter( SensorSample.sensor_reading_time.between(start_time, end_time)) elif start_time is None and end_time is not None or start_time is not None and end_time is None: raise InvalidUsage( "Both start_time and end_time are required for sensor_reading_time queries" ) results = bundle_query.all() return jsonify(bundles=[r.serialize() for r in results])
def __init__(self): # Read preferences self.conf = None with open(PATH_TO_CONF_FILE, 'r') as f: self.conf = json.load(f) if not self.conf: raise InvalidUsage('Bad settings file')
def new_user(): try: login = request.headers['X-Auth-Login'] except KeyError: raise InvalidUsage('Invalid data', status_code=400) l = [x for x in users if x.login == login] if len(l): raise InvalidUsage('User alredy exists', status_code=401) u = User(login) t = u.gen_token() users.append(u) res = jsonify({ 'token': t }) return res
def pay_to_bank(): content = request.json if 'coins' not in content: raise InvalidUsage("Coins not given", status_code=400) with lock: game.pay_to_bank(get_player(), int(content['coins'])) return "", 200
def return_card_to_deck(): content = request.json if 'cardId' not in content: raise InvalidUsage("Card id not given", status_code=400) with lock: game.return_card_to_deck(get_player(), content['cardId']) return "", 200
def playlist(display_id): # check playlist exists try: playlist = db.session.query(Playlist).filter_by( display_id=display_id).one() except NoResultFound as ex: raise InvalidUsage('No playlist found for id: {}'.format(display_id)) # check for playlist_mode show_id = request.args.get('show_id', None) password = request.args.get('password', None) if show_id is None or password is None: session['playlist_mode'] = 'readonly' # check show exists and associates to playlist try: show = db.session.query(Show).filter_by(display_id=show_id, password=password).one() if playlist in show.playlists: session['playlist_mode'] = 'edit' else: # TODO log session['playlist_mode'] = 'readonly' except NoResultFound as ex: # TODO log session['playlist_mode'] = 'readonly' return jsonify(display_id=display_id, songs=[song.as_dict() for song in playlist.songs])
def api() -> str: errors = validate_message(request) if errors is not None: print(errors) raise InvalidUsage(errors) activities = request.json.get("activities") response = {"activities": activities} return jsonify(response)
def validated_dt(date_str): """ Create and return a datetime object based on the given string. If the string is inappropriate, raise an error with helpful message. """ try: return datetime.datetime.strptime(date_str, '%Y%m%d') except ValueError: raise InvalidUsage("Incorrect date format, should be: YYYYMMDD")
def chowly_order(): url = 'https://api.chowlyinc.com/api/toos/v2/orders' headers = {'api-key': CHOWLY_API_KEY} if request.method == 'POST': input = request.get_json() order = input.get("order") if order == None: raise InvalidUsage('Order details not found') res = requests.post(url, headers=headers, json=order) return res.json() order_id = request.args.get('orderId') if order_id == None: raise InvalidUsage('Order id not found') res = requests.get("{}/{}".format(url, order_id), headers=headers) return res.json()
def available_datasets(f): """ Return list of all datasets available in resource f. """ try: datasets = sorted(list(f)) except ValueError: raise InvalidUsage("Problem with processing WTK datasets.") return datasets
def search(): try: search_json = request.get_json() except Exception as ex: raise InvalidUsage('Invalid JSON') spotify = spotipy.Spotify() search_term = search_json['search_term'] results = spotify.search(q=search_term, type='track,artist', limit=20) return jsonify(results)
def playlists_by_show_id(show_display_id): # check show exists try: show = db.session.query(Show).filter_by( display_id=show_display_id).one() except NoResultFound as ex: raise InvalidUsage('No show found for id: {}'.format(show_display_id)) playlist_disp_ids = [x.display_id for x in show.playlists] return jsonify(playlists=playlist_disp_ids)
def move_token(): content = request.json if 'token_name' not in content: raise InvalidUsage("Token name not given", status_code=400) if 'token_index' not in content: raise InvalidUsage("Token index not given", status_code=400) player_name_dst = None if 'player_name_dst' in content: player_name_dst = content['player_name_dst'] try: token_index = int(content['token_index']) with lock: game.move_token(content['token_name'], token_index, player_name_dst) except Exception: raise InvalidUsage("Token index should be a number", status_code=400) return "", 200
def get_online(): try: token = request.headers['X-Auth-Token'] except KeyError: raise InvalidUsage('Invalid auth', status_code=401) (res, login) = auth(token) if not res: raise InvalidUsage('Invalid auth', status_code=401) l = [] for k in online: if k != login: l.append({ 'login': k, 'ip': online[k][0], 'port': online[k][1], }) res = jsonify(l) return res
def available_heights(f, prefix="windspeed"): """ Return list of all heights available in resource f -- datasets named "<prefix>_XXm", where XX is a number. """ prefix = prefix.rstrip("_") + "_" try: heights = sorted([ int(attr.replace(prefix, "").rstrip("m")) for attr in list(f) if prefix in attr ]) except ValueError: raise InvalidUsage("Problem with processing WTK heights.") return heights
def distribute_cards(): response_object = {"status": "success"} request_data = request.get_json() print(request_data) if not request_data: # TODO magic strings raise InvalidUsage("You must supply number_of_decks in payload", status_code=405) number_of_decks = int(request_data["number_of_decks"]) # TODO: only expose one function from game to distribute cards cards = game.prepare_cards_for_distribution(number_of_decks) game.distribute_cards(cards) broadcast_cards_update() return jsonify(response_object)
def add_song(display_id): # check playlist_mode playlist_mode = session.get('playlist_mode') if playlist_mode != 'edit': raise InvalidUsage("Can't add songs in readonly mode") # check playlist exists try: playlist = db.session.query(Playlist).filter_by( display_id=display_id).one() except NoResultFound as ex: raise InvalidUsage('No playlist found for id: {}'.format(display_id)) try: song_data = request.get_json() except Exception as ex: raise InvalidUsage('Invalid JSON') song = Song(**song_data) playlist.songs.append(song) db.session.add(song) db.session.commit() return 'OK'
def new_playlist(): show_id = request.args.get('show_id') password = request.args.get('password') # check show exists try: show = db.session.query(Show).filter_by(display_id=show_id, password=password).one() except NoResultFound as ex: raise InvalidUsage('No show found for id: {}'.format(show_id)) playlist = Playlist() show.playlists.append(playlist) db.session.add(playlist) db.session.commit() return jsonify(display_id=playlist.display_id)
def prepare_winddirection(height, lat, lon, start_date, stop_date, hsds_f, debug=False): debug_info = [] heights = available_heights(hsds_f, prefix="winddirection") datasets = available_datasets(hsds_f) if height < np.min(heights) or height > np.max(heights): raise InvalidUsage(("Requested height is outside " "of allowed range: [%.2f, %.2f]" % (np.min(heights), np.max(heights)))) tidx, timestamps = time_indices(hsds_f, start_date, stop_date) if debug: debug_info.append("Specified height: %f" % height) debug_info.append("Specified lat: %f" % lat) debug_info.append("Specified lon: %f" % lon) debug_info.append("Specified start_date: %s" % str(start_date)) debug_info.append("Specified stop_date: %s" % str(stop_date)) debug_info.append("Available heights: %s" % str(heights)) debug_info.append("Time indices: %s" % str(tidx)) debug_info.append("Available datasets: %s" % str(datasets)) tile_df = find_tile(hsds_f, lat, lon, radius=1) nearest_h = heights[np.abs(np.array(heights) - height).argmin()] wd_dset = hsds_f["winddirection_%dm" % int(nearest_h)] neighbor_ts_df = extract_ts_for_neighbors(tile_df.head(1), tidx, wd_dset) neighbor_ts_df.columns = ["winddirection"] neighbor_ts_df["timestamp"] = timestamps neighbor_ts_df["timestamp"] = neighbor_ts_df["timestamp"].astype(str) finalized_df = neighbor_ts_df[["timestamp", "winddirection"]].reset_index(drop=True) if debug: debug_info += df2strings(tile_df) debug_info += df2strings(neighbor_ts_df) return (finalized_df, debug_info)
def connected_hsds_file(request, config): """ Return a file object that corresponds to the HSDS resource specified in the request (using domain, endpoint, username, password, and api_key parameters). This function processes request parameters, uses default values for 'domain' and 'endpoint' if they aren't specified, and uses demo API key (rate-limited) if none of the relevant parameters is specified; it uses read-only mode. """ if 'domain' in request.args: domain = request.args['domain'] else: domain = config["hsds"]["domain"] if 'endpoint' in request.args: endpoint = request.args['endpoint'] else: endpoint = config["hsds"]["endpoint"] if ('username' not in request.args) and ('password' not in request.args)\ and ('api_key' not in request.args): username = config["hsds"]["username"] password = config["hsds"]["password"] api_key = config["hsds"]["api_key"] else: if 'username' in request.args: username = request.args['username'] else: raise InvalidUsage(("HSDS username is not specified. " "Specify all three--username, password, " "and api_key--or remove all three from " "request to use demo credentials.")) if 'password' in request.args: password = request.args['password'] else: raise InvalidUsage(("HSDS password is not specified. " "Specify all three--username, password, " "and api_key--or remove all three from " "request to use demo credentials.")) if 'api_key' in request.args: api_key = request.args['api_key'] else: raise InvalidUsage(("HSDS api_key is not specified. " "Specify all three--username, password, " "and api_key--or remove all three from " "request to use demo credentials.")) try: f = h5pyd.File(domain=domain, endpoint=endpoint, username=username, password=password, api_key=api_key, mode='r') return f except OSError: raise InvalidUsage(("Failed to access specified HSDS resource. " "Check credentials: " "domain, endpoint, username, password, api_key. " "It could be a transient HSDS connection issue. " "Try again later."), status_code=403)