当前位置: 首页>>代码示例>>Python>>正文


Python simplejson.loads方法代码示例

本文整理汇总了Python中django.utils.simplejson.loads方法的典型用法代码示例。如果您正苦于以下问题:Python simplejson.loads方法的具体用法?Python simplejson.loads怎么用?Python simplejson.loads使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.utils.simplejson的用法示例。


在下文中一共展示了simplejson.loads方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ResultLoader

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def ResultLoader(request):
  try:
    last_loader_id = LastLoaderId()
    results = [result for result in simplejson.loads(request.raw_post_data)
               if result[0] > last_loader_id]
    logging.info('last_loader_id=%d, num results to add=%d',
                 last_loader_id, len(results))
    for result in results:
      loader_id, ip, user_agent_string, created_timestamp, test_scores = result
      created = datetime.datetime.utcfromtimestamp(created_timestamp)

      ResultParent.AddResult(TEST_SET, ip, user_agent_string, test_scores,
                             loader_id=loader_id, created=created,
                             is_import=True)
      last_loader_id = loader_id
  except Exception, e:
    logging.info('exception: %s', traceback.format_exc())
    return http.HttpResponse('exception: %s' % str(e), mimetype='text/plain',
                             status=500) 
开发者ID:elsigh,项目名称:browserscope,代码行数:21,代码来源:bulkloader.py

示例2: testCreated

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def testCreated(self):
    created_base = datetime.datetime(2009, 9, 9, 9, 9, 0)
    keys = []
    for scores in ((0, 10, 100), (1, 20, 200)):
      ip = '1.2.2.%s' % scores[1]
      result = ResultParent.AddResult(
          self.test_set, ip, mock_data.GetUserAgentString('Firefox 3.5'),
          'apple=%s,banana=%s,coconut=%s' % scores,
          created=created_base + datetime.timedelta(seconds=scores[1]))
      keys.append(str(result.key()))
    params = {
          'model': 'ResultParent',
          'created': created_base + datetime.timedelta(seconds=15),
          }
    response = self.client.get('/admin/data_dump_keys', params)
    self.assertEqual(200, response.status_code)
    response_params = simplejson.loads(response.content)
    self.assertEqual(None, response_params['bookmark'])
    self.assertEqual(keys[1:], response_params['keys']) 
开发者ID:elsigh,项目名称:browserscope,代码行数:21,代码来源:test_admin.py

示例3: extend_access_token

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def extend_access_token(self, app_id, app_secret):
        """
        Extends the expiration time of a valid OAuth access token. See
        <https://developers.facebook.com/roadmap/offline-access-removal/
        #extend_token>

        """
        args = {
            "client_id": app_id,
            "client_secret": app_secret,
            "grant_type": "fb_exchange_token",
            "fb_exchange_token": self.access_token,
        }
        response = urllib2.urlopen("https://graph.facebook.com/oauth/"
                                   "access_token?" +
                                   urllib.parse.urlencode(args)).read().decode('utf-8')
        query_str = parse_qs(response)
        if "access_token" in query_str:
            result = {"accesstoken": query_str["access_token"][0]}
            if "expires" in query_str:
                result["expire"] = query_str["expires"][0]
            return result
        else:
            response = json.loads(response)
            raise GraphAPIError(response) 
开发者ID:MicroPyramid,项目名称:django-simple-forum,代码行数:27,代码来源:facebook.py

示例4: get_access_token_from_code

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def get_access_token_from_code(code, redirect_uri, app_id, app_secret):

    args = {
        "code": code,
        "redirect_uri": redirect_uri,
        "client_id": app_id,
        "client_secret": app_secret,
    }
    # We would use GraphAPI.request() here, except for that the fact
    # that the response is a key-value pair, and not JSON.
    response = urllib2.urlopen("https://graph.facebook.com/oauth/access_token" +
                              "?" + urllib.parse.urlencode(args)).read().decode('utf-8')
    query_str = parse_qs(response)
    if "access_token" in query_str:
        result = {"access_token": query_str["access_token"][0]}
        if "expires" in query_str:
            result["expires"] = query_str["expires"][0]
        return result
    else:
        jsonResponse = json.loads(str(response))
        # response = json.loads(response)
        encoding = response.info().get_content_charset('utf8')
        data = json.loads(response.read().decode(encoding))
        return data 
开发者ID:MicroPyramid,项目名称:django-simple-forum,代码行数:26,代码来源:facebook.py

示例5: get

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def get(self, **params):
        "Get the XML response for the passed `params`."
        params['api_key'] = self.apiKey
        params['format'] = 'json'
        params['api_sig'] = self._sign(params)

        json_data = openURL(SERVICE_URL, params).read()

        # LOG.debug("JSON response: \n%s" % json)
        if _use_jsonlib:
            data = dottedDict('ROOT', json.loads(json_data.decode('utf-8')))
        else:
            data = dottedJSON(json_data.decode('utf-8'))
        rsp = data.rsp

        if rsp.stat == 'fail':
            raise RTMAPIError(f'API call failed - {rsp.err.msg} ({rsp.err.code})')
        else:
            return rsp 
开发者ID:getting-things-gnome,项目名称:gtg,代码行数:21,代码来源:rtm.py

示例6: parse_json

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def parse_json(self, page, exactly_one=True):
        if not isinstance(page, basestring):
            page = util.decode_page(page)
        doc = json.loads(page)
        places = doc.get('Placemark', [])

        if len(places) == 0:
            # Got empty result. Parse out the status code and raise an error if necessary.
            status = doc.get("Status", [])
            status_code = status["code"]
            self.check_status_code(status_code)
            return None
        elif exactly_one and len(places) != 1:
            raise ValueError("Didn't find exactly one placemark! " \
                             "(Found %d.)" % len(places))

        def parse_place(place):
            location = place.get('address')
            longitude, latitude = place['Point']['coordinates'][:2]
            return (location, (latitude, longitude))
        
        if exactly_one:
            return parse_place(places[0])
        else:
            return [parse_place(place) for place in places] 
开发者ID:blackye,项目名称:luscan-devel,代码行数:27,代码来源:google.py

示例7: parse_json

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def parse_json(self, page, exactly_one=True):
        '''Returns location, (latitude, longitude) from json feed.'''
        if not isinstance(page, basestring):
            page = util.decode_page(page)
        self.doc = json.loads(page)
        places = self.doc.get('results', [])
    
        if not places:
            check_status(self.doc.get('status'))
            return None
        elif exactly_one and len(places) != 1:
            raise ValueError(
                "Didn't find exactly one placemark! (Found %d)" % len(places))
    
        def parse_place(place):
            '''Get the location, lat, lng from a single json place.'''
            location = place.get('formatted_address')
            latitude = place['geometry']['location']['lat']
            longitude = place['geometry']['location']['lng']
            return (location, (latitude, longitude))
        
        if exactly_one:
            return parse_place(places[0])
        else:
            return [parse_place(place) for place in places] 
开发者ID:blackye,项目名称:luscan-devel,代码行数:27,代码来源:googlev3.py

示例8: __getitem__

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def __getitem__(self, keyname):
        """
        Get item from session data.

        keyname: The keyname of the mapping.
        """
        # flash messages don't go in the datastore

        if self.integrate_flash and (keyname == 'flash'):
            return self.flash.msg
        if keyname in self.cache:
            # UNPICKLING CACHE return pickle.loads(str(self.cache[keyname]))
            return self.cache[keyname]
        if keyname in self.cookie_vals:
            return self.cookie_vals[keyname]
        if hasattr(self, "session"):
            data = self._get(keyname)
            if data:
                #UNPICKLING CACHE self.cache[keyname] = data.content
                self.cache[keyname] = pickle.loads(data.content)
                return pickle.loads(data.content)
            else:
                raise KeyError(str(keyname))
        raise KeyError(str(keyname)) 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:26,代码来源:sessions.py

示例9: __init__

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def __init__(self, http_response, response_body=None):
        """Sets the HTTP information in the error.

        Args:
          http_response: The response from the server, contains error information.
          response_body: string (optional) specified if the response has already
                         been read from the http_response object.
        """
        body = response_body or http_response.read()

        self.status = http_response.status
        self.reason = http_response.reason
        self.body = body
        self.headers = atom.http_core.get_headers(http_response)

        self.error_msg = 'Invalid response %s.' % self.status
        try:
            json_from_body = simplejson.loads(body.decode('utf-8'))
            if isinstance(json_from_body, dict):
                self.error_msg = json_from_body.get('error', self.error_msg)
        except (ValueError, JSONDecodeError):
            pass 
开发者ID:dvska,项目名称:gdata-python3,代码行数:24,代码来源:gauth.py

示例10: yatse_api

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def yatse_api(request):
    try:
        if request.method != 'PROPFIND':
            api_login(request)

    except PermissionDenied:
        return HttpResponseForbidden(request.META.get('HTTP_API_USER'))

    if request.method == 'PROPPATCH':
        data = json.loads(request.body)
        if 'ticket' in data and 'method' in data:
            if data['method'] == 'notify':
                tickets_participants.objects.filter(ticket=data['ticket'], user=request.user).update(seen=True)
                return HttpResponse('OK')
        return HttpResponseNotFound('invalid method\n\n%s' % request.body)

    elif request.method == 'PROPFIND':
        fields = buildYATSFields([])
        return JsonResponse(fields[0], safe=False)

    elif request.method == 'SEARCH':
        return JsonResponse(YATSSearch(request), safe=False)

    else:
        return HttpResponseNotFound('invalid method') 
开发者ID:mediafactory,项目名称:yats,代码行数:27,代码来源:views.py

示例11: reports

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def reports(request):
    if 'report' in request.GET:
        rep = tickets_reports.objects.get(pk=request.GET['report'])
        add_breadcrumbs(request, request.GET['report'], '@', caption=rep.name[:20])
        request.session['last_search'] = json.loads(rep.search)
        return HttpResponseRedirect('/tickets/search/?report=%s' % request.GET['report'])

    if 'delReport' in request.GET:
        tickets_reports.objects.get(c_user=request.user, pk=request.GET['delReport']).delete(user=request.user)
        return HttpResponseRedirect('/reports/')

    reps = tickets_reports.objects.filter(active_record=True, c_user=request.user).order_by('name')

    paginator = Paginator(reps, 10)
    page = request.GET.get('page')
    try:
        rep_lines = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        rep_lines = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        rep_lines = paginator.page(paginator.num_pages)

    return render(request, 'tickets/reports.html', {'lines': rep_lines}) 
开发者ID:mediafactory,项目名称:yats,代码行数:27,代码来源:tickets.py

示例12: GetResultUriString

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def GetResultUriString(request, category):
    """Parses out a category result string from the request, w/ goo.gl and hash.
    Args:
        request: The request object.
        category: The category.
    Returns:
        The result string in the request url, expanding goo.gl or hashes.
    """
    results_key = '%s_results' % category
    # allow "results" for user_tests.
    results_uri_string = request.GET.get(results_key,
                                         request.GET.get('results', None))
    # Adding a check for None since bots are sending it.
    if results_uri_string and results_uri_string != 'None':
        memcache_str = memcache.get(key=results_uri_string,
                                    namespace=RESULTS_STRING_MEMCACHE_NS)
        if memcache_str:
            results_uri_string = memcache_str

        # If the results_uri_string is a goo.gl link, expand it.
        elif re.search('goo.gl', results_uri_string):
            googl_req_url = ('https://www.googleapis.com/urlshortener/v1/url?'
                             'key=%s&shortUrl=%s' %
                             (settings.GOOGLE_API_KEY, results_uri_string))
            #logging.info('SENDING GOO.GL REQ: %s' % googl_req_url)
            response = urlfetch.fetch(googl_req_url)
            json = simplejson.loads(response.content)
            qs = urlparse.parse_qs(urlparse.urlparse(json['longUrl']).query)
            results_uri_string = qs[results_key][0]
    #logging.info('GetResultUriString RESULTS_URI_STR: %s' % results_uri_string)
    # Stupid web bot crap.
    if results_uri_string == 'None':
        results_uri_string = None
    return results_uri_string 
开发者ID:elsigh,项目名称:browserscope,代码行数:36,代码来源:util.py

示例13: WebPagetest

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def WebPagetest(request, key):
  """Sends an API request to run one's test page on WebPagetest.org."""
  test = models.user_test.Test.get_mem(key)
  if not test:
    msg = 'No test was found with test_key %s.' % key
    return http.HttpResponseServerError(msg)

  current_user = users.get_current_user()
  if (test.user.key().name() != current_user.user_id() and not
        users.is_current_user_admin()):
      return http.HttpResponse('You can\'t play with tests you don\'t own')

  # Help users autorun their tests by adding autorun=1 to the test url.
  test_url_parts = list(urlparse.urlparse(test.url))
  test_url_query = dict(cgi.parse_qsl(test_url_parts[4]))
  test_url_query.update({'autorun': '1'})
  test_url_parts[4] = urllib.urlencode(test_url_query)
  test_url = urlparse.urlunparse(test_url_parts)

  # TODO(elsigh): callback url.
  webpagetest_url = ('%s&url=%s&notify=%s' %
                     (WEBPAGETEST_URL, test_url,
                      urllib.quote('elsigh@gmail.com')))

  webpagetests = {}
  # See http://goo.gl/EfK1r for WebPagetest instructions.
  for location in WEBPAGETEST_LOCATIONS:
    url = '%s&location=%s' % (webpagetest_url, location)
    response = urlfetch.fetch(url)
    json = simplejson.loads(response.content)
    webpagetests[location] = json

  params = {
    'test': test,
    'webpagetests': webpagetests
  }
  return util.Render(request, 'user_test_webpagetest.html', params) 
开发者ID:elsigh,项目名称:browserscope,代码行数:39,代码来源:user_tests.py

示例14: testEmptyUpload

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def testEmptyUpload(self):
    results = [
        [111, '12.1.1.1', USER_AGENT_STRINGS['Firefox 3.5'], 1234455,
         [('testDisplay', 100), ('testVisibility', 2)]],
        [222, '12.2.2.2', USER_AGENT_STRINGS['Firefox 3.0.9'], 1234456,
         [('testDisplay', 200), ('testVisibility', 1)]],
        ]
    results = []
    raw_post_data = simplejson.dumps(results)
    response = self.client.post('/network/loader', raw_post_data,
                                content_type='application/jsonrequest')
    self.assertEqual(200, response.status_code)

    last_loader_id = simplejson.loads(response.content)
    self.assertEqual(0, last_loader_id) 
开发者ID:elsigh,项目名称:browserscope,代码行数:17,代码来源:test_network_bulkuploader.py

示例15: testNonExistentKeyIsMarkedLost

# 需要导入模块: from django.utils import simplejson [as 别名]
# 或者: from django.utils.simplejson import loads [as 别名]
def testNonExistentKeyIsMarkedLost(self):
    for model in ('ResultParent', 'UserAgent'):
      params = {
          'keys': 'agt1YS1wcm9maWxlcnIRCxIJVXNlckFnZW50GN6JIgw',
          'model': model}
      response = self.client.get('/admin/data_dump', params)
      self.assertEqual(200, response.status_code)
      response_params = simplejson.loads(response.content)
      expected_data = [{
          'model_class': model,
          'lost_key': 'agt1YS1wcm9maWxlcnIRCxIJVXNlckFnZW50GN6JIgw',
          }]
      self.assertEqual(expected_data, response_params['data']) 
开发者ID:elsigh,项目名称:browserscope,代码行数:15,代码来源:test_admin.py


注:本文中的django.utils.simplejson.loads方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。