예제 #1
0
파일: tst.py 프로젝트: daltonserey/tst
    def send_answer(self, answer, key):
        s = requests.session()
        s = CacheControl(s, cache=FileCache(os.path.expanduser('~/.tst/cache')))

        url = "%s/%s/answers" % (self.url, key)
        data = data2json(answer).encode('utf-8')
        tokens = JsonFile(os.path.expanduser('~/.tst/tokens.json'))
        headers = {"Authorization": "Bearer %s" % tokens.get(self.name)}
        try:
            response = s.post(url, headers=headers, data=data, allow_redirects=True)
        except requests.ConnectionError:
            _assert(False, "Connection failed... check your internet connection (1)")

        return response
예제 #2
0
파일: tst.py 프로젝트: daltonserey/tst
    def get(self, key):
        s = requests.session()
        s = CacheControl(s, cache=FileCache(os.path.expanduser('~/.tst/cache')))

        url = "%s/%s" % (self.url, key)
        headers = {}
        tokens = JsonFile(os.path.expanduser('~/.tst/tokens.json'))
        token = tokens.get(self.name)
        if token:
            headers['Authorization'] = 'Bearer %s' % token

        try:
            response = s.get(url, headers=headers, allow_redirects=True)
        except requests.ConnectionError:
            _assert(False, "Connection failed... check your internet connection")

        if not response.ok:
            self.last_error = response.status_code
            self.last_response = response
            return None

        response.encoding = 'utf-8'
        try:
            resource = response.json()
            resource['_response'] = response
            validate_tst_object(resource)

        except ValueError:
            #_assert(False, "Resource is not valid json")
            return None

        except AssertionError as e:
            print(resource)
            _assert(False, "Not a TST Object: %s" % e.message)

        return resource
예제 #3
0
파일: tst.py 프로젝트: daltonserey/tst
    def urls(self):
        s = requests.session()
        s = CacheControl(s, cache=FileCache(os.path.expanduser('~/.tst/cache')))

        headers = {}
        tokens = JsonFile(os.path.expanduser('~/.tst/tokens.json'))
        token = tokens.get(self.name)
        try:
            response = s.get(self.url, allow_redirects=True)
        except requests.ConnectionError:
            _assert(False, "Connection failed... check your internet connection")

        if not response.ok:
            return None

        response.encoding = 'utf-8'
        try:
            resource = response.json()
            resource['_response'] = response

        except ValueError:
            return None

        return resource
예제 #4
0
파일: tst.py 프로젝트: daltonserey/tst
    def get_directory(self, key):
        s = requests.session()
        s = CacheControl(s, cache=FileCache(os.path.expanduser('~/.tst/cache')))

        url = "%s/%s/tst.yaml" % (self.url, key)
        headers = {}
        tokens = JsonFile(os.path.expanduser('~/.tst/tokens.json'))
        token = tokens.get(self.name)
        if token:
            headers['Authorization'] = 'Bearer %s' % token

        try:
            response = s.get(url, headers=headers, allow_redirects=True)
        except requests.ConnectionError:
            _assert(False, "Connection failed... check your internet connection (1)")

        # TODO: Split method in two. The first part performs a fetch,
        #       while the second part (below) processes the response and
        #       possibly fetches further files. We could have a simple
        #       fetch method/funcion and a more high level get_directory
        #       that uses such method. In fact, the get() method above can
        #       also be improved with such a refactoring.

        # process response
        if not response.ok:
            self.last_error = response.status_code
            self.last_response = response
            return None

        response.encoding = 'utf-8'
        try:
            import yaml
            resource = yaml.load(response.text, Loader=yaml.FullLoader)
            resource['_response'] = response

        except Exception as e:
            cprint(YELLOW, "Failed parsing yaml: %s" % url)
            cprint(YELLOW, e.message)
            raise e

        # gather files
        files = resource.get('files') or []
        files.append({
            "name": "tst.yaml",
            "content": response.text,
            "mode": "ro"
        })

        ## add text file if required
        if 'text' in resource and is_single_line_string(resource['text']):
            files.append({
                "name": resource['text'],
                "content": '%s/%s/%s' % (self.url, key, resource['text']),
                "mode": "ro"
            })

        ## add included files
        files_filenames = [f['name'] for f in files]
        for fspec in resource['include']:
            filename, category, mode = parse_file_spec(fspec)
            if filename not in files_filenames:
                files.append({
                    'name': filename,
                    'content': '%s/%s/%s' % (self.url, key, filename),
                    'mode': mode
                })
            else:
                entry = next(e for e in files if e['name'] == filename)
                entry['mode'] = mode

        ## fetch missing files
        for f in files:
            if f['content'].startswith('http://') or f['content'].startswith('https://'):
                f['content'] = fetch_file('%s/%s/%s' % (self.url, key, f['name']), encoding='utf-8')

        return {
            'kind': 'activity',
            'files': files,
        }