def playback(): msg = 'Request to upload file received' print(request.files) # Validate file if 'file' not in request.files: return error(400, 'Validation Error', 'You must supply a file') # Validate display name if 'displayName' not in request.form: return error(400, 'Validation Error', 'You must supply a display name') if 'fileName' not in request.form: return error(400, 'Validation Error', 'You must supply a file name') display_name = request.form['displayName'] file_name = request.form['fileName'] file = request.files['file'] try: save_file(str(file_name), file) playback_recording(file_name) delete_file('sounds/' + str(file_name)) except Exception as e: return error(500, 'Internal Server Error', str(e)) return success(200, msg)
def parse(): api.args = argparser.parse_args() api.config = ConfigParser.SafeConfigParser(dict_type=collections.OrderedDict) api.config.optionxform = str ini_files = [ os.path.join(api.root, 'etc', 'vespa.ini'), os.path.join(api.root, 'etc', 'vespa.ini.local') ] if api.args.ini: ini_files.append(api.args.ini) try: ok = api.config.read(ini_files) except ConfigParser.ParsingError as e: raise api.error('Unable to parse file: %s', e) if not ok: raise api.error('Unable to read config file') logging.basicConfig( format = '%(asctime)s %(levelname)-8s %(message)s', datefmt = '%Y-%m-%d %H:%M:%S', level = logging.INFO )
def parse(): api.args = argparser.parse_args() api.config = ConfigParser.SafeConfigParser( dict_type=collections.OrderedDict) api.config.optionxform = str ini_files = [ os.path.join(api.root, 'etc', 'vespa.ini'), os.path.join(api.root, 'etc', 'vespa.ini.local') ] if api.args.ini: ini_files.append(api.args.ini) try: ok = api.config.read(ini_files) except ConfigParser.ParsingError as e: raise api.error('Unable to parse file: %s', e) if not ok: raise api.error('Unable to read config file') logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
def post_recording(): if 'file' not in request.files: return error(400, 'Validation Error', 'You must supply a file!') if 'fileName' not in request.form: return error(400, 'Validation Error', 'You must supply a file name') file_name = request.form['fileName'] file = request.files['file'] try: save_file(str(file_name), file) except Exception as e: return error(500, 'Internal Server Error', str(e)) return success(200, 'Recording saved succesfully!')
def api_channel_stats(channel_id: int): with DB.connect() as db: channel = get_channel(db, channel_id) if not channel: return error('Resource not found', 404) options, errors = ApiChannelStatsSchema().load(request.args) if errors: return jsonify(errors=errors), 400 history_from = options['from'] history_to = options['to'] history_averaging = options['average'] items = get_channel_stats(db, channel_id, history_from, history_to, history_averaging) label_format = '%H:%M' if history_averaging == 1 else '%d.%m.%Y %H:00' items = ((time.strftime(label_format), round(value, 2) if value else None) for time, value in items) title = channel.name unit = channel.unit labels, values = zip(*items) return jsonify(title=title, unit=unit, labels=labels, values=values)
def api_channel_settings(channel_id: int): with DB.connect() as db: channel = get_channel(db, channel_id) if not channel: return error('Channel not found') data, errors = ChannelSchema().dump(channel) return jsonify(data) if not errors else internal_error()
def device_settings(device_id: int): with DB.connect() as db: device = get_device(db, device_id) if not device: return error('Device not found') data, errors = DeviceSchema().dump(device) return jsonify(data) if not errors else internal_error()
def api_upload(): """Upload a JSON formatted post to the database.""" if request.method == "POST": success, c = db.post(request.form["post"].rstrip()) if success: return api.success() else: return api.error("Error uploading post to database", 500)
def initialize(): engine = api.config.get('storage', 'engine') path = 'api.storage.engines.' + engine try: mod = __import__(path) except ImportError as e: raise api.error('Unknown storage engine: %s [%s]', engine, e) for sub in path.split('.')[1:]: mod = getattr(mod, sub) try: db = getattr(mod, 'Database') except AttributeError: raise api.error('Bad storage engine: %s', engine) api.db = db() logging.info('Storage engine: %s', engine)
def get_recording(): print('Getting a voice recording from the server!') length = request.args.get('length') if length is None: length = 10 if int(length) < 0: return error(400, 'Validation Error', 'Recording length must be greater than 0!') try: do_recording(int(length)) time.sleep(int(length)) return send_from_directory('sounds/', filename='captured_recording.wav', as_attachment=True) except Exception as e: return error(500, 'Internal Server Error', str(e)) return success(200, 'Recorded succesfully!')
def volume(): msg = 'Changing volume on teddbyear' print(msg) change_in_vol = request.args.get('changeInVolume') if change_in_vol is None: change_in_vol = 0 try: change_volume(int(change_in_vol)) except Exception as e: return error(500, 'Internal Server Error', str(e)) return success(200, msg)
def api_post(): """Return a post in JSON for the API.""" id_n = request.args.get("id") raw = request.args.get("raw") try: id_n = int(id_n) except: return api.error("Invalid ID number", 404) raw_post = db.read_by_id_n(id_n) if raw_post == False: return api.error("Empty raw_post", 404) if raw != None: post_text = raw_post["post"] else: post_text = strip_signature(raw_post["post"]) return api.ok(api.format_post(raw_post, post_text))
def playbackFile(file): msg = 'Playing a specific audio recording %s' % str(file) print(msg) #if 'fileName' not in request.form: #return error(400, 'Validation Error', 'You must supply a file name') #file = request.form['fileName'] try: playback_recording(file) except Exception as e: return error(500, 'Internal Server Error', str(e)) return success(200, msg)
def fondren_rooms_api(): """ Function selector for API interface for Fondren reservation system. First validates passed parameters, then calls either the database version or the live version of the reservation API. """ # Parameters from URL api_key = request.args.get("key", "") filter_room = request.args.get("room", "") live = request.args.get("live", "").lower() == "true" # Initial error handling # Check valid API key if not api.is_api_key_valid(api_key): return api.error("Invalid or unauthorized API key") # Check valid (int-castable) year if len(filter_room) > 0: try: int(filter_room) except: return api.error("Invalid room number " + filter_room) # Choose whether to use the cached results or get live results return fondren_api_live(filter_room) if live else fondren_api_database( filter_room)
def main(): addr = api.args.addr or api.config.get('server', 'address') port = api.args.port or api.config.getint('server', 'port') try: with open(os.path.join(api.root, 'etc', 'cookie.secret')) as fp: cookie_secret = fp.read(44) except IOError: logging.critical('Could not read cookie.secret') return -1 websocket_handler = api.handlers.WSRouter(api.handlers.WebSocket, '/ws') patterns = [(r'/', api.handlers.Index), (r'/login', api.handlers.Login), (r'/logout', api.handlers.Logout), (r'/download/(.*)', api.handlers.Download) ] + websocket_handler.urls settings = dict(static_path=os.path.join(api.root, 'static'), template_path=os.path.join(api.root, 'server_templates'), cookie_secret=cookie_secret, login_url='/login', debug=api.config.get('main', 'debug')) api.app = tornado.web.Application(patterns, **settings) websocket_handler.set_application(api.app) api.app.sockets = {} try: api.app.listen(port, addr) except Exception as e: raise api.error('Could not listen on address: %s', e) logging.info('Listening on %s:%d', addr, port) try: api.ioloop.start() except KeyboardInterrupt: api.ioloop.stop() return 0
def process_request(self, request): if getattr(settings, 'APPEND_SLASH') and getattr( settings, 'REMOVE_SLASH'): raise ImproperlyConfigured( "APPEND_SLASH and REMOVE_SLASH may not both be True.") old_url = request.path_info #path_info only includes path, query information if getattr(settings, 'REMOVE_SLASH', False) and old_url[-1] == "/": urlconf = getattr(request, 'urlconf', None) new_url = old_url[:-1] #If the url with a / would 404 and without a slash wouldn't if (not urlresolvers.is_valid_path( old_url, urlconf)) and urlresolvers.is_valid_path( new_url, urlconf): if settings.DEBUG and request.method == 'POST': if (old_url.startswith("/api/")): return api.error( "You made a POST request to a URL ending with a slash. Please repeat your request without the slash." ) else: raise RuntimeError(( "" "You called this URL via POST, but the URL ends in a " "slash and you have REMOVE_SLASH set. Django can't " "redirect to the non-slash URL while maintaining POST " "data. Change your form to point to %s (without a " "trailing slash), or set REMOVE_SLASH=False in your " "Django settings.") % (new_url)) query_data = re.match(r'^[^?]*(\?.*)?$', request.build_absolute_uri()).group( 1) or "" #The ? and everything after return http.HttpResponsePermanentRedirect(new_url + query_data)
import random import api try: import sqlite3 except ImportError: raise api.error('Missing sqlite3 module\n') # Utility function to create a unique id def uid(bits=31): return random.randrange(2**bits) class Database: def __init__(self, path): self.conn = sqlite3.connect(path) self.conn.row_factory = sqlite3.Row self.cursor = self.conn.cursor() def Find(self, table, params=None, sort=None): statement = 'SELECT * FROM ' + table if params: statement += ' WHERE ' + params if sort: statement += '' self.cursor.execute(statement) return self.cursor.fetchall()
def fondren_hours_api(): # Check valid API key if not api.is_api_key_valid(request.args.get("key", "")): return api.error("Invalid or unauthorized API key") return get_open_hours()
import random import api try: import sqlite3 except ImportError: raise api.error('Missing sqlite3 module\n') # Utility function to create a unique id def uid(bits=31): return random.randrange(2**bits) class Database: def __init__(self, path): self.conn = sqlite3.connect(path) self.conn.row_factory = sqlite3.Row self.cursor = self.conn.cursor() def Find(self, table, params=None, sort=None): statement = 'SELECT * FROM ' + table; if params: statement += ' WHERE ' + params if sort: statement += '' self.cursor.execute(statement) return self.cursor.fetchall() def FindOne(self, table, _id):