User Tools

Site Tools


python:sample_program_for_highlighting
#!/usr/bin/python3
"""Audio API endpoint handling (Flask-restful)."""
 
 
 
from flask import abort
from flask_restful import Resource, reqparse, inputs
from api_models import audio_model
 
class AudioAPI(Resource):
    """API endpoint for controlling volume level and mute."""
 
    def __init__(self, model):
        # mocked data for volume control
        self.model = model
        super(AudioAPI, self).__init__()
 
    # API methods
    def get(self):
        """Handler for GET requests.
        Return full state."""
        return {
            'level': self.model.get_level(),
            'isMute': self.model.get_mute()
        }, 200, {'Access-Control-Allow-Origin': '*'}  # <-temporary access ctl.
 
    def put(self):
        """Handler for PUT requests.
        Set state passed in header JSON. Return changed new state.
        {'level': <integer>} will set the volume level
        {'isMute': <boolean>} will set the mute"""
        parser = reqparse.RequestParser() # used to parse requests
        parser.add_argument('isMute') # a JSON boolean, not a py bool.
        parser.add_argument('level',
                            type=int,
                            help="must be between %s and %s." %
                            (audio_model.MIN_LEVEL, audio_model.MAX_LEVEL))
        # get request arguments
        args = parser.parse_args()
        new_state = {}
 
        if args.isMute is not None:
            try:
                # convert arg to boolean, set and add to new_state:
                is_mute = inputs.boolean(args.isMute)
                new_state['isMute'] = self.model.set_mute(is_mute)
            except ValueError as err:
                abort(400, str(err))
 
        # additional level validation
        if args.level is not None:
            try:
                was_muted = self.model.get_mute()  # get pre-update mute state
                new_state['level'] = self.model.set_level(args.level)
                if was_muted: # add changed mute state to returned data.
                    new_state['isMute'] = self.model.get_mute()
            except ValueError as err:
                abort(400, str(err))
 
        return new_state, \
            200, {'Access-Control-Allow-Origin': '*'}  # <-temporary access ctl.
python/sample_program_for_highlighting.txt · Last modified: 2016/07/27 22:32 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki