def test_get_access_token(self):
    S = 2  # number of seconds in which the token expires
    token_response_first = {'access_token': 'first_token', 'expires_in': S}
    token_response_second = {'access_token': 'second_token', 'expires_in': S}
    http = HttpMockSequence([
        ({'status': '200'}, simplejson.dumps(token_response_first)),
        ({'status': '200'}, simplejson.dumps(token_response_second)),
    ])

    token = self.credentials.get_access_token(http=http)
    self.assertEqual('first_token', token.access_token)
    self.assertEqual(S - 1, token.expires_in)
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_first, self.credentials.token_response)

    token = self.credentials.get_access_token(http=http)
    self.assertEqual('first_token', token.access_token)
    self.assertEqual(S - 1, token.expires_in)
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_first, self.credentials.token_response)

    time.sleep(S)
    self.assertTrue(self.credentials.access_token_expired)

    token = self.credentials.get_access_token(http=http)
    self.assertEqual('second_token', token.access_token)
    self.assertEqual(S - 1, token.expires_in)
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_second, self.credentials.token_response)
  def test_get_access_token(self):
    S = 2  # number of seconds in which the token expires
    token_response_first = {'access_token': 'first_token', 'expires_in': S}
    token_response_second = {'access_token': 'second_token', 'expires_in': S}
    http = HttpMockSequence([
        ({'status': '200'}, simplejson.dumps(token_response_first)),
        ({'status': '200'}, simplejson.dumps(token_response_second)),
    ])

    token = self.credentials.get_access_token(http=http)
    self.assertEqual('first_token', token.access_token)
    self.assertEqual(S - 1, token.expires_in)
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_first, self.credentials.token_response)

    token = self.credentials.get_access_token(http=http)
    self.assertEqual('first_token', token.access_token)
    self.assertEqual(S - 1, token.expires_in)
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_first, self.credentials.token_response)

    time.sleep(S)
    self.assertTrue(self.credentials.access_token_expired)

    token = self.credentials.get_access_token(http=http)
    self.assertEqual('second_token', token.access_token)
    self.assertEqual(S - 1, token.expires_in)
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_second, self.credentials.token_response)
  def test_get_access_token(self):
    token_response_first = {'access_token': 'first_token', 'expires_in': 1}
    token_response_second = {'access_token': 'second_token', 'expires_in': 1}
    http = HttpMockSequence([
        ({'status': '200'}, simplejson.dumps(token_response_first)),
        ({'status': '200'}, simplejson.dumps(token_response_second)),
    ])

    self.assertEqual('first_token',
                     self.credentials.get_access_token(http=http))
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_first, self.credentials.token_response)

    self.assertEqual('first_token',
                     self.credentials.get_access_token(http=http))
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_first, self.credentials.token_response)

    time.sleep(1)
    self.assertTrue(self.credentials.access_token_expired)

    self.assertEqual('second_token',
                     self.credentials.get_access_token(http=http))
    self.assertFalse(self.credentials.access_token_expired)
    self.assertEqual(token_response_second, self.credentials.token_response)
示例#4
0
    def print_result(self, result):
        """Pretty-print the result of the command.

        The default behavior is to dump a formatted JSON encoding
        of the result.

        Args:
            result: The JSON-serializable result to print.
        """
        # We could have used the pprint module, but it produces
        # noisy output due to all of our keys and values being
        # unicode strings rather than simply ascii.
        print json.dumps(result, sort_keys=True, indent=2)
  def test_extract_success(self):
    body = {'foo': 'bar'}
    payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
    jwt = 'stuff.' + payload + '.signature'

    extracted = _extract_id_token(jwt)
    self.assertEqual(extracted, body)
示例#6
0
            def get(self):
                error = self.request.get('error')
                if error:
                    errormsg = self.request.get('error_description', error)
                    self.response.out.write(
                        'The authorization request failed: %s' %
                        _safe_html(errormsg))
                else:
                    user = users.get_current_user()
                    decorator._create_flow(self)
                    credentials = decorator.flow.step2_exchange(
                        self.request.params)
                    StorageByKeyName(CredentialsModel, user.user_id(),
                                     'credentials').put(credentials)
                    redirect_uri = _parse_state_value(
                        str(self.request.get('state')), user)

                    if decorator._token_response_param and credentials.token_response:
                        resp_json = simplejson.dumps(
                            credentials.token_response)
                        redirect_uri = util._add_query_parameter(
                            redirect_uri, decorator._token_response_param,
                            resp_json)

                    self.redirect(redirect_uri)
示例#7
0
    def post(self, data_source_id, data_view_id):
        try:
            current_user = User.get_by_google_id(self.session['current_user'])
            data_source  = DataSource.get_by_id(int(data_source_id))
            data_view    = DataView.get_by_id(int(data_view_id))
            payload      = json.loads(self.request.POST["payload"])

            if data_source is None:
                raise ValueError("No Data Source exists with id %s" % data_source_id)

            if not data_source.user.key() == current_user.key():
                raise ValueError("Data Source with id %s does not belong to user '%s'" % (data_source_id, current_user.profile_slug))

            if data_view is None:
                raise ValueError("No Data View exists with id %s" % data_source_id)

            if not data_view.data_source.key() == data_source.key():
                raise ValueError("Data View with id %s does not belong to Data Source with id %s" % (data_view_id, data_source_id))

            if "template" in payload.keys(): 
                data_view.template = payload['template']
                data_view.modified_at = DT.now()
                data_view.put()

            self.response.write('{"response":"success","body":%s}' % json.dumps(data_view.to_dict(), ensure_ascii=False))

        except ValueError as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(404)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem updating data source"}')
            self.response.set_status(500)
    def callback_handler(self, request):
        from django import http
        import logging
        logging.info('callback_handler')
        self.request = request
        error = request.GET.get('error')
        if error:
            errormsg = request.GET.get('error')
            return http.HttpResponse('The authorization request failed: %s' %
                                     errormsg)
        else:
            user = users.get_current_user()
            self._create_flow(self)
            credentials = self.flow.step2_exchange(
                {'code': str(request.GET.get('code', ''))})
            self._storage_class(self._credentials_class,
                                None,
                                self._credentials_property_name,
                                user=user).put(credentials)
            redirect_uri = _parse_state_value(str(request.GET.get('state')),
                                              user)

            if self._token_response_param and credentials.token_response:
                resp_json = simplejson.dumps(credentials.token_response)
                redirect_uri = util._add_query_parameter(
                    redirect_uri, self._token_response_param, resp_json)
                import logging
                logging.info(redirect_uri)
            return http.HttpResponseRedirect(redirect_uri)
示例#9
0
    def get(self, data_source_id, data_view_id):
        try:
            current_user = User.get_by_google_id(self.session['current_user'])
            data_source  = DataSource.get_by_id(int(data_source_id))
            data_view    = DataView.get_by_id(int(data_view_id))

            if data_source is None:
                raise ValueError("No Data Source exists with id %s" % data_source_id)

            if not data_source.user.key() == current_user.key():
                raise ValueError("Data Source with id %s does not belong to user '%s'" % (data_source_id, current_user.profile_slug))

            if data_view is None:
                raise ValueError("No Data View exists with id %s" % data_source_id)

            if not data_view.data_source.key() == data_source.key():
                raise ValueError("Data View with id %s does not belong to Data Source with id %s" % (data_view_id, data_source_id))

            self.response.write('{"response":"success","body":%s}' % json.dumps(data_view.to_dict(default_template=True), ensure_ascii=False))

        except ValueError as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(404)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem fetching data source"}')
            self.response.set_status(500)
示例#10
0
    def test_extract_failure(self):
        body = {'foo': 'bar'}
        payload = base64.urlsafe_b64encode(
            simplejson.dumps(body).encode()).decode('ascii').strip('=')
        jwt = 'stuff.' + payload

        self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
    def test_extract_success(self):
        body = {"foo": "bar"}
        payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip("=")
        jwt = "stuff." + payload + ".signature"

        extracted = _extract_id_token(jwt)
        self.assertEqual(body, extracted)
示例#12
0
  def _to_json(self, strip):
    """Utility function that creates JSON repr. of a Credentials object.

    Args:
      strip: array, An array of names of members to not include in the JSON.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    """
    t = type(self)
    d = copy.copy(self.__dict__)
    for member in strip:
      if member in d:
        del d[member]
    if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime):
      d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT)
    # Add in information we will need later to reconsistitue this instance.
    d['_class'] = t.__name__
    d['_module'] = t.__module__
    for k, v in d.items():
      if type(v) is bytes:
        d[k] = v.decode('utf-8')

    return simplejson.dumps(d)
示例#13
0
    def get(self, data_source_id):
        try:
            current_user = User.get_by_google_id(self.session['current_user'])
            data_source  = DataSource.get_by_id(int(data_source_id))

            if data_source is None:
                raise ValueError("No Data Source exists with id %s" % data_source_id)

            if not data_source.user.key() == current_user.key():
                raise ValueError("Data Source with id %s does not belong to user '%s'" % (data_source_id, current_user.profile_slug))

            data_views = data_source.fetch_data_views()
            response = {
                'total_results': len(data_views),
                'data_views': [ds.to_dict() for ds in data_views]
            }
            self.response.write('{"response":"success","body":%s}' % json.dumps(response, ensure_ascii=False))

        except ValueError as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(404)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem fetching data sources"}')
            self.response.set_status(500)
示例#14
0
    def post(self, data_source_id):
        try:
            payload      = json.loads(self.request.POST["payload"])
            current_user = User.get_by_google_id(self.session['current_user'])
            data_source  = DataSource.get_by_id(int(data_source_id))

            if data_source is None:
                raise ValueError("No Data Source exists with id %s" % data_source_id)

            if not data_source.user.key() == current_user.key():
                raise ValueError("Data Source with id %s does not belong to user '%s'" % (data_source_id, current_user.profile_slug))

            if "description" in payload.keys(): data_source.description = payload['description']
            if "licence"     in payload.keys(): data_source.licence     = payload['licence']
            if "slug"        in payload.keys(): data_source.slug        = payload['slug']
            if "tags"        in payload.keys(): data_source.tags        = payload['tags']
            if "tbl_stars"   in payload.keys(): data_source.tbl_stars   = int(payload['tbl_stars'])
            if "title"       in payload.keys(): data_source.title       = payload['title']
            data_source.modified_at = DT.now()
            data_source.put()

            self.response.write('{"response":"success","body":%s}' % json.dumps(data_source.to_dict(), ensure_ascii=False))

        except ValueError as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(404)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem updating data source"}')
            self.response.set_status(500)
  def get(self):
    """Returns stats of managed Compute Engine instances for Admin UI."""
    load_entries = []
    instance_list = ComputeEngineController(
        decorator.credentials).ListInstances()
    all_load_info = LoadInfo.GetAll()

    # First, list managed instances whose Compute Engine status is found.
    for instance in instance_list:
      instance_name = instance['name']
      if instance_name in all_load_info:
        info = all_load_info[instance_name]
        load_entries.append({
            'host': instance_name,
            'ipaddress': info.get(LoadInfo.IP_ADDRESS, ''),
            'status': instance['status'],
            'load': info.get(LoadInfo.LOAD, 0),
            'force_set': info.get(LoadInfo.FORCE, False),
        })
        del all_load_info[instance_name]

    # Then, list managed instances without Compute Engine status.
    for name, info in all_load_info.items():
      load_entries.append({
          'host': name,
          'ipaddress': info.get(LoadInfo.IP_ADDRESS, ''),
          'status': 'NOT FOUND',
          'load': info.get(LoadInfo.LOAD, 0),
          'force_set': info.get(LoadInfo.FORCE, False),
      })

    self.response.out.write(json.dumps(load_entries))
示例#16
0
    def test_extract_success(self):
        body = {'foo': 'bar'}
        payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
        jwt = 'stuff.' + payload + '.signature'

        extracted = _extract_id_token(jwt)
        self.assertEqual(extracted, body)
 def get(self):
   """Returns an available server's IP address in JSON format."""
   ip = LoadInfo.GetIdleInstanceIpAddress()
   if not ip:
     ip = ''
   self.response.out.write(json.dumps({'ipaddress': ip}))
   IpAddressRequestLog(client_ip=self.request.remote_addr,
                       server_ip=ip).put()
示例#18
0
文件: http.py 项目: Blurjp/HuangDaxi
 def to_json(self):
     """Returns a JSON representation of the HttpRequest."""
     d = copy.copy(self.__dict__)
     if d['resumable'] is not None:
         d['resumable'] = self.resumable.to_json()
     del d['http']
     del d['postproc']
     return simplejson.dumps(d)
 def get(self):
     """Returns an available server's IP address in JSON format."""
     ip = LoadInfo.GetIdleInstanceIpAddress()
     if not ip:
         ip = ''
     self.response.out.write(json.dumps({'ipaddress': ip}))
     IpAddressRequestLog(client_ip=self.request.remote_addr,
                         server_ip=ip).put()
示例#20
0
文件: http.py 项目: Blurjp/HuangDaxi
 def to_json(self):
   """Returns a JSON representation of the HttpRequest."""
   d = copy.copy(self.__dict__)
   if d['resumable'] is not None:
     d['resumable'] = self.resumable.to_json()
   del d['http']
   del d['postproc']
   return simplejson.dumps(d)
示例#21
0
 def to_json(self):
     """Serialize record to JSON."""
     d = {
         'request_id': self.request_id,
         'access_token': self.access_token,
         'refresh_token': self.refresh_token,
         'refresh_date': self.refresh_date.strftime(DATE_FORMAT)
     }
     return simplejson.dumps(d)
示例#22
0
 def to_json(self):
     """Serialize record to JSON."""
     d = {
         'request_id': self.request_id,
         'access_token': self.access_token,
         'refresh_token': self.refresh_token,
         'refresh_date': self.refresh_date.strftime(DATE_FORMAT)
     }
     return simplejson.dumps(d)
示例#23
0
def from_dict(container):
    """
    Create a Credentials object from a dictionary.

    The dictionary is first converted to JSON by the native implementation
    to ensure it is converted correctly and make updates to the oauth2client module
    easier.
    """
    jsonRepr = simplejson.dumps(container)
    return Credentials.new_from_json(jsonRepr)
示例#24
0
 def request(self, uri, method="GET", body=None, headers=None, redirections=1, connection_type=None):
     resp, content = self._iterable.pop(0)
     if content == "echo_request_headers":
         content = headers
     elif content == "echo_request_headers_as_json":
         content = simplejson.dumps(headers)
     elif content == "echo_request_body":
         content = body
     elif content == "echo_request_uri":
         content = uri
     return httplib2.Response(resp), content
示例#25
0
    def get(self):
        try:
            # NB we have to decode "credentials" as it is stored as a string in the DB
            current_user = User.get_by_google_id(self.session['current_user']).to_dict()
            current_user["credentials"] = json.loads(current_user["credentials"])
            self.response.write('{"response":"success","body":%s}' % json.dumps(current_user, ensure_ascii=False))

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem fetching user profile"}')
            self.response.set_status(500)
示例#26
0
 def test_exchange_code_for_token(self):
   token = 'asdfghjkl'
   payload =simplejson.dumps({'access_token': token, 'expires_in': 3600})
   http = HttpMockSequence([
     ({'status': '200'}, payload),
   ])
   credentials = credentials_from_code(self.client_id, self.client_secret,
       self.scope, self.code, redirect_uri=self.redirect_uri,
       http=http)
   self.assertEquals(credentials.access_token, token)
   self.assertNotEqual(None, credentials.token_expiry)
示例#27
0
 def get_game_message(self):
     # The gameUpdate object is sent to the client to render the state of a game.
     gameUpdate = {
       # 'board': self.game.board,
       # 'userX': self.game.userX.user_id(),
       # 'userO': '' if not self.game.userO else self.game.userO.user_id(),
       # 'moveX': self.game.moveX,
       # 'winner': self.game.winner,
       't**s': nice
     }
     return simplejson.dumps(gameUpdate)
 def test_exchange_code_for_token(self):
   token = 'asdfghjkl'
   payload =simplejson.dumps({'access_token': token, 'expires_in': 3600})
   http = HttpMockSequence([
     ({'status': '200'}, payload),
   ])
   credentials = credentials_from_code(self.client_id, self.client_secret,
       self.scope, self.code, redirect_uri=self.redirect_uri,
       http=http)
   self.assertEquals(credentials.access_token, token)
   self.assertNotEqual(None, credentials.token_expiry)
示例#29
0
 def test_token_refresh_success(self):
   for status_code in REFRESH_STATUS_CODES:
     token_response = {'access_token': '1/3w', 'expires_in': 3600}
     http = HttpMockSequence([
         ({'status': status_code}, ''),
         ({'status': '200'}, simplejson.dumps(token_response)),
         ({'status': '200'}, 'echo_request_headers'),
     ])
     http = self.credentials.authorize(http)
     resp, content = http.request('http://example.com')
     self.assertEqual('Bearer 1/3w', content['Authorization'])
     self.assertFalse(self.credentials.access_token_expired)
     self.assertEqual(token_response, self.credentials.token_response)
 def test_token_refresh_success(self):
   for status_code in REFRESH_STATUS_CODES:
     token_response = {'access_token': '1/3w', 'expires_in': 3600}
     http = HttpMockSequence([
         ({'status': status_code}, ''),
         ({'status': '200'}, simplejson.dumps(token_response)),
         ({'status': '200'}, 'echo_request_headers'),
     ])
     http = self.credentials.authorize(http)
     resp, content = http.request('http://example.com')
     self.assertEqual('Bearer 1/3w', content['Authorization'])
     self.assertFalse(self.credentials.access_token_expired)
     self.assertEqual(token_response, self.credentials.token_response)
    def get(self):
        """Returns stats of game instances for non logged-in users."""
        load_entries = []
        all_load_info = LoadInfo.GetAll()

        for name, info in all_load_info.items():
            load_entries.append({
                'host': name,
                'ipaddress': info.get(LoadInfo.IP_ADDRESS, ''),
                'load': info.get(LoadInfo.LOAD, 0),
            })

        self.response.out.write(json.dumps(load_entries))
  def get(self):
    """Returns stats of game instances for non logged-in users."""
    load_entries = []
    all_load_info = LoadInfo.GetAll()

    for name, info in all_load_info.items():
      load_entries.append({
          'host': name,
          'ipaddress': info.get(LoadInfo.IP_ADDRESS, ''),
          'load': info.get(LoadInfo.LOAD, 0),
      })

    self.response.out.write(json.dumps(load_entries))
示例#33
0
    def upload(self, id, name, create=False):
        logger = logging.getLogger()
        foldername = os.path.join(self.folder, name)
        logger.info('prepare folder: %s' % foldername)
        manifest_path = os.path.join(foldername, MANIFEST)
        mfile = open(manifest_path, 'rb')
        data = simplejson.loads(mfile.read())
        mfile.close()
        # import files in the directory
        for i, fileInProject in enumerate(data['files']):
            extension = '.html'  # default
            if fileInProject['type'] == 'server_js': extension = '.gs'
            filename = '%s%s' % (fileInProject['name'], extension)
            logger.info('- file%04d: %s' % (i, filename))
            f = open(os.path.join(foldername, filename), 'rb')
            fileInProject['source'] = f.read().decode(
                'utf-8')  # to unicode json
            f.close()
        # last import manifest.json
        logger.info('- manifest: %s' % MANIFEST)
        mfile = open(manifest_path, 'wb')
        mfile.write(simplejson.dumps(data))
        mfile.close()

        mbody = MediaFileUpload(manifest_path,
                                mimetype=SCRIPT_TYPE,
                                resumable=True)
        if create:  # create new Apps Script project
            body = {
                'title': name,
                'mimeType': SCRIPT_TYPE,
                'description': name
            }
            fileobj = self.service.files().insert(body=body,
                                                  media_body=mbody).execute()
            id = fileobj['id']
            # export manifest.json to refresh new file id
            download_url = fileobj['exportLinks'][SCRIPT_TYPE]
            resp, content = self.service._http.request(download_url)
            if resp.status != 200:
                raise Exception('An error occurred: %s' % resp)
            logger.info('- refresh: %s' % MANIFEST)
            mfile = open(manifest_path, 'wb')
            mfile.write(content)  # raw string
            mfile.close()
        else:  # overwrite exists Apps Script project
            body = {'mimeType': SCRIPT_TYPE}
            fileobj = self.service.files().update(fileId=id,
                                                  body=body,
                                                  media_body=mbody).execute()
        return (id, fileobj)
示例#34
0
    def get(self, google_sheets_id, worksheet_key):
        try:
            data = google_api.get_cell_data(self.current_user().credentials, google_sheets_id, worksheet_key)
            self.response.write('{"response":"success","body":%s}' % json.dumps(data, ensure_ascii=False))
        
        except google_api.GoogleAPIException as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(500)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem connecting to Google Drive"}')
            self.response.set_status(500)
示例#35
0
    def get(self):
        try:
            current_user = User.get_by_google_id(self.session['current_user'])
            data_sources = current_user.fetch_data_sources()
            response = {
                'total_results': len(data_sources),
                'data_sources': [ds.to_dict() for ds in data_sources]
            }
            self.response.write('{"response":"success","body":%s}' % json.dumps(response, ensure_ascii=False))

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem fetching data sources"}')
            self.response.set_status(500)
示例#36
0
文件: http.py 项目: Blurjp/HuangDaxi
  def to_json(self):
    """Create a JSON representation of a MediaInMemoryUpload.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    """
    t = type(self)
    d = copy.copy(self.__dict__)
    del d['_body']
    d['_class'] = t.__name__
    d['_module'] = t.__module__
    d['_b64body'] = base64.b64encode(self._body)
    return simplejson.dumps(d)
  def test_exchange_id_token_fail(self):
    body = {'foo': 'bar'}
    payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
    jwt = (base64.urlsafe_b64encode('stuff')+ '.' + payload + '.' +
           base64.urlsafe_b64encode('signature'))

    http = HttpMockSequence([
      ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
       "refresh_token":"8xLOxBtZp8",
       "id_token": "%s"}""" % jwt),
      ])

    credentials = self.flow.step2_exchange('some random code', http=http)
    self.assertEqual(credentials.id_token, body)
示例#38
0
文件: http.py 项目: Blurjp/HuangDaxi
    def to_json(self):
        """Create a JSON representation of a MediaInMemoryUpload.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    """
        t = type(self)
        d = copy.copy(self.__dict__)
        del d['_body']
        d['_class'] = t.__name__
        d['_module'] = t.__module__
        d['_b64body'] = base64.b64encode(self._body)
        return simplejson.dumps(d)
示例#39
0
  def test_exchange_id_token_fail(self):
    body = {'foo': 'bar'}
    payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
    jwt = (base64.urlsafe_b64encode('stuff')+ '.' + payload + '.' +
           base64.urlsafe_b64encode('signature'))

    http = HttpMockSequence([
      ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
       "refresh_token":"8xLOxBtZp8",
       "id_token": "%s"}""" % jwt),
      ])

    credentials = self.flow.step2_exchange('some random code', http=http)
    self.assertEqual(credentials.id_token, body)
示例#40
0
    def get(self):
        try:
            page_token = self.request.GET["page_token"] if 'page_token' in self.request.GET.keys() else None
            query = "trashed = false and hidden = false and mimeType = 'application/vnd.google-apps.spreadsheet'"
            data  = google_api.list_drive_files(self.current_user().credentials, query=query, page_token=page_token)
            self.response.write('{"response":"success","body":%s}' % json.dumps(data, ensure_ascii=False))
        
        except google_api.GoogleAPIException as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(500)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"Unknown problem connecting to Google Drive"}')
            self.response.set_status(500)
示例#41
0
 def request(self, uri,
             method='GET',
             body=None,
             headers=None,
             redirections=1,
             connection_type=None):
   resp, content = self._iterable.pop(0)
   if content == 'echo_request_headers':
     content = headers
   elif content == 'echo_request_headers_as_json':
     content = simplejson.dumps(headers)
   elif content == 'echo_request_body':
     content = body
   elif content == 'echo_request_uri':
     content = uri
   return httplib2.Response(resp), content
示例#42
0
文件: http.py 项目: Blurjp/HuangDaxi
  def _to_json(self, strip=None):
    """Utility function for creating a JSON representation of a MediaUpload.

    Args:
      strip: array, An array of names of members to not include in the JSON.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    """
    t = type(self)
    d = copy.copy(self.__dict__)
    if strip is not None:
      for member in strip:
        del d[member]
    d['_class'] = t.__name__
    d['_module'] = t.__module__
    return simplejson.dumps(d)
示例#43
0
文件: http.py 项目: Blurjp/HuangDaxi
    def _to_json(self, strip=None):
        """Utility function for creating a JSON representation of a MediaUpload.

    Args:
      strip: array, An array of names of members to not include in the JSON.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    """
        t = type(self)
        d = copy.copy(self.__dict__)
        if strip is not None:
            for member in strip:
                del d[member]
        d['_class'] = t.__name__
        d['_module'] = t.__module__
        return simplejson.dumps(d)
    def test_exchange_id_token_fail(self):
        body = {"foo": "bar"}
        payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip("=")
        jwt = base64.urlsafe_b64encode("stuff") + "." + payload + "." + base64.urlsafe_b64encode("signature")

        http = HttpMockSequence(
            [
                (
                    {"status": "200"},
                    """{ "access_token":"SlAV32hkKG",
       "refresh_token":"8xLOxBtZp8",
       "id_token": "%s"}"""
                    % jwt,
                )
            ]
        )

        credentials = self.flow.step2_exchange("some random code", http)
        self.assertEquals(body, credentials.id_token)
示例#45
0
 def request(self, uri,
             method='GET',
             body=None,
             headers=None,
             redirections=1,
             connection_type=None):
   resp, content = self._iterable.pop(0)
   if content == 'echo_request_headers':
     content = headers
   elif content == 'echo_request_headers_as_json':
     content = simplejson.dumps(headers)
   elif content == 'echo_request_body':
     if hasattr(body, 'read'):
       content = body.read()
     else:
       content = body
   elif content == 'echo_request_uri':
     content = uri
   return httplib2.Response(resp), content
示例#46
0
  def upload(self, id, name, create=False):
    logger = logging.getLogger()
    foldername = os.path.join(self.folder, name)
    logger.info('prepare folder: %s' % foldername)
    manifest_path = os.path.join(foldername, MANIFEST)
    mfile = open(manifest_path, 'rb')
    data = simplejson.loads(mfile.read())
    mfile.close()
    # import files in the directory
    for i, fileInProject in enumerate(data['files']):
      extension = '.html' # default
      if fileInProject['type'] == 'server_js': extension = '.gs'
      filename = '%s%s' % (fileInProject['name'], extension)
      logger.info('- file%04d: %s' % (i, filename))
      f = open(os.path.join(foldername, filename), 'rb')
      fileInProject['source'] = f.read().decode('utf-8') # to unicode json
      f.close()
    # last import manifest.json
    logger.info('- manifest: %s' % MANIFEST)
    mfile = open(manifest_path, 'wb')
    mfile.write(simplejson.dumps(data))
    mfile.close()

    mbody = MediaFileUpload(manifest_path, mimetype=SCRIPT_TYPE, resumable=True)
    if create: # create new Apps Script project
      body = {'title': name, 'mimeType': SCRIPT_TYPE, 'description': name}
      fileobj = self.service.files().insert(
        body=body, media_body=mbody).execute()
      id = fileobj['id']
      # export manifest.json to refresh new file id
      download_url = fileobj['exportLinks'][SCRIPT_TYPE]
      resp, content = self.service._http.request(download_url)
      if resp.status != 200: raise Exception('An error occurred: %s' % resp)
      logger.info('- refresh: %s' % MANIFEST)
      mfile = open(manifest_path, 'wb')
      mfile.write(content) # raw string
      mfile.close()
    else: # overwrite exists Apps Script project
      body = {'mimeType': SCRIPT_TYPE}
      fileobj = self.service.files().update(
        fileId=id, body=body, media_body=mbody).execute()
    return (id, fileobj)
示例#47
0
    def post(self):
        try:
            payload = json.loads(self.request.POST["payload"])
            preview = render_data(payload['template'], payload['data'])
            data = {
                'data': payload['data'],
                'template': payload['template'],
                'preview': preview
            }
            self.response.write('{"response":"success","body":%s}' % json.dumps(data, ensure_ascii=False))

        except ValueError as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"%s"}' % e)
            self.response.set_status(404)

        except Exception as e:
            log_api_error(self, e)
            self.response.write('{"response":"error","body":"A probelm occured when generating the preview"}')
            self.response.set_status(500)
示例#48
0
  def _to_json(self, strip):
    """Utility function that creates JSON repr. of a Credentials object.

    Args:
      strip: array, An array of names of members to not include in the JSON.

    Returns:
       string, a JSON representation of this instance, suitable to pass to
       from_json().
    """
    t = type(self)
    d = copy.copy(self.__dict__)
    for member in strip:
      if member in d:
        del d[member]
    if 'token_expiry' in d and isinstance(d['token_expiry'], datetime.datetime):
      d['token_expiry'] = d['token_expiry'].strftime(EXPIRY_FORMAT)
    # Add in information we will need later to reconsistitue this instance.
    d['_class'] = t.__name__
    d['_module'] = t.__module__
    return simplejson.dumps(d)
    def get(self):
        """Returns stats of managed Compute Engine instances for Admin UI."""
        load_entries = []
        instance_list = ComputeEngineController(
            decorator.credentials).ListInstances()
        all_load_info = LoadInfo.GetAll()

        # First, list managed instances whose Compute Engine status is found.
        for instance in instance_list:
            instance_name = instance['name']
            if instance_name in all_load_info:
                info = all_load_info[instance_name]
                load_entries.append({
                    'host':
                    instance_name,
                    'ipaddress':
                    info.get(LoadInfo.IP_ADDRESS, ''),
                    'status':
                    instance['status'],
                    'load':
                    info.get(LoadInfo.LOAD, 0),
                    'force_set':
                    info.get(LoadInfo.FORCE, False),
                })
                del all_load_info[instance_name]

        # Then, list managed instances without Compute Engine status.
        for name, info in all_load_info.items():
            load_entries.append({
                'host': name,
                'ipaddress': info.get(LoadInfo.IP_ADDRESS, ''),
                'status': 'NOT FOUND',
                'load': info.get(LoadInfo.LOAD, 0),
                'force_set': info.get(LoadInfo.FORCE, False),
            })

        self.response.out.write(json.dumps(load_entries))
示例#50
0
    method_to_call = getattr(resource_to_call(), main_options.method)
    url_options, still_leftover_options = parseUrlArgs(
        method_object=method_object, argv=leftover_options[1:])
    body = parseBodyArgs(discovery_object, method_object,
                         still_leftover_options)
    if body:
        url_options.body = {}
        for key in body.keys():
            if body[key] not in [None, u'']:
                url_options.body[key] = body[key]
    if main_options.media_body:
        url_options.media_body = main_options.media_body
    try:
        result = method_to_call(**vars(url_options)).execute()
    except apiclient.errors.HttpError, e:
        print e.resp['status'], simplejson.loads(e.content)['error']['message']
        return
    except TypeError, e:
        print e
        return
    if url_options.fields:
        print result[url_options.fields]
    else:
        print simplejson.dumps(result,
                               sort_keys=True,
                               indent=2,
                               separators=(',', ': '))


if __name__ == '__main__':
    main(sys.argv)
示例#51
0
def _http_request(*args, **kwargs):
  resp = httplib2.Response({'status': '200'})
  content = simplejson.dumps({'access_token': 'bar'})

  return resp, content
示例#52
0
 def request(self, token_uri, method, body, headers, *args, **kwargs):
   self.body = body
   self.headers = headers
   return (self, simplejson.dumps(self.content))
示例#53
0
 def serialize(self, body_value):
     if (isinstance(body_value, dict) and 'data' not in body_value
             and self._data_wrapper):
         body_value = {'data': body_value}
     return simplejson.dumps(body_value)
示例#54
0
def _urlsafe_b64encode(data):
  return base64.urlsafe_b64encode(
      simplejson.dumps(data, separators = (',', ':'))\
          .encode('UTF-8')).rstrip('=')