32.4.2. 逐步指南

以下是实现此客户所需自定义分析的步骤:

  1. 检索应用的完整列表。此操作需要分页。

    def api_call_applications_list(domain, provider_key)
      done = false
      res = Array.new
      page = 1
    
          while !done
        url = "https://#{domain}/admin/api/applications.xml?provider_key=#{provider_key}&page=#{page}&per_page=100"
        page += 1
        response = RestClient.get url
        raise Exception.new("Wrong response code (#{response.code}) in request #{url}") if response.code!=200
        document = Nokogiri::XML(response.to_str)    done = document.xpath("applications/@current_page").text == document.xpath("applications/@total_pages").text
        document.xpath("//application").each do |item|
          app = Hash.new
          app["created_at"] = DateTime.parse(item.xpath("created_at").text)
          app["plan_name"] = item.xpath("plan/name").text
          app["service_id"] = item.xpath("plan/service_id").text
          app["account_id"] = item.xpath("user_account_id").text
          app["id"] = item.xpath("id").text
          res << app
        end
      end
      return res
    end
  2. 过滤不符合标准的应用程序,即计划必须"评估"且必须更新 10 天。

    def filter_applications(domain, provider_key, plan_name, num_of_days)
      res = api_call_applications_list(domain, provider_key)
      res.each do |item|
        res.delete(item) if item["plan_name"] != plan_name
        res.delete(item) if item["created_at"] > (DateTime.now - num_of_days)
      end
      return res
    end
  3. 然后,对于满足此条件的每个应用程序,获得其使用情况,即应用程序在最后 10 天内有多少点击次数。

    def api_call_application_usage(domain, provider_key, application_id, metric, from, to, granularity)
      url = "https://#{domain}/stats/applications/#{application_id}/usage.xml?provider_key=#{provider_key}&metric_name=#{metric}&since=#{from}&until=#{to}&granularity=#{granularity}"
      response = RestClient.get url
      raise Exception.new("Wrong response code (#{response.code}) in request #{url}") if response.code!=200
      document = Nokogiri::XML(response.to_str)
      return document.xpath("//usage/data/values").text.split(",")
    end
  4. 交叉将应用程序引用到帐户,因为开发人员的信息存储在帐户对象中。

    def api_call_account_read(domain, provider_key, account_id)
      url = "https://#{domain}/admin/api/accounts/#{account_id}.xml?provider_key=#{provider_key}"
      response = RestClient.get url
      raise Exception.new("Wrong response code (#{response.code}) in request #{url}") if response.code!=200
      document = Nokogiri::XML(response.to_str)
      account = Hash.new
      account["email"] = document.xpath("//users/user/email").text
      account["name"] = document.xpath("//users/user/first_name").text + " " + document.xpath("//users/user/last_name").text
      return account
    end

    现在,您只需要将所有内容放在一起,脚本即完成。您有一个脚本,可获取 3scale 内置分析中尚未提供的信息。您还可以 以 gist 形式获得完整的脚本