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


Python urlfetch.fetch方法代码示例

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


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

示例1: call_method

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def call_method(method, data):
  data = json.dumps(data)
  try:
    result = urlfetch.fetch(
        BASE_URL.format(token=TOKEN, method=method),
        payload=data,
        method=urlfetch.POST,
        deadline=10,
        headers={'Content-Type': 'application/json'})
  except DeadlineExceededError as e:
    logging.exception(e)
    return None
  if result.status_code == 200:
    return json.loads(result.content)
  else:
    logging.error(result.content)
    return None 
开发者ID:phil-r,项目名称:hackernewsbot,代码行数:19,代码来源:telegram.py

示例2: call_method

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def call_method(method, data):
  data.update({'key': TOKEN})
  data = json.dumps(data)
  try:
    result = urlfetch.fetch(
        BASE_URL.format(method=method, api_key=TOKEN),
        payload=data,
        method=urlfetch.POST,
        deadline=10,
        headers={'Content-Type': 'application/json'})
  except DeadlineExceededError as e:
    logging.exception(e)
    return None
  if result.status_code == 200:
    return json.loads(result.content)
  else:
    logging.error(result.content)
    return None 
开发者ID:phil-r,项目名称:hackernewsbot,代码行数:20,代码来源:googl.py

示例3: call_method

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def call_method(method, data):
  data.update({'access_token': TOKEN})
  data = urllib.urlencode(data)
  try:
    result = urlfetch.fetch(
        BASE_URL.format(method=method, qs=data),
        method=urlfetch.GET,
        deadline=10)
  except DeadlineExceededError as e:
    logging.exception(e)
    return None
  if result.status_code == 200:
    return json.loads(result.content).get('data')
  else:
    logging.error(result.content)
    return None 
开发者ID:phil-r,项目名称:hackernewsbot,代码行数:18,代码来源:bitly.py

示例4: _new_fixed_fetch

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def _new_fixed_fetch(validate_certificate):

    def fixed_fetch(
        url,
        payload=None,
        method="GET",
        headers={},
        allow_truncated=False,
        follow_redirects=True,
        deadline=None,
    ):
        return fetch(
            url,
            payload=payload,
            method=method,
            headers=headers,
            allow_truncated=allow_truncated,
            follow_redirects=follow_redirects,
            deadline=deadline,
            validate_certificate=validate_certificate,
        )

    return fixed_fetch 
开发者ID:remg427,项目名称:misp42splunk,代码行数:25,代码来源:__init__.py

示例5: ClearDatastore

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def ClearDatastore(request):
    """Clears data in the datastore, many at a time (for admins only)."""
    clear = (None, 'None')
    atatime = 10

    msg = ''
    query = db.Query(clear[0])
    rows = query.fetch(atatime)
    length = len(rows)
    if length is 0:
        msg += 'No more rows to delete<br>'
    else:
        msg += 'Deleting %s %s<br>' % (length, clear[1])
        db.delete(rows)
        query = db.Query(clear[0])
        more = query.fetch(1)
        if len(more) is not 0:
            msg += 'Now do it again!'
            msg += '<script>window.location.href="/reflows/clear_datastore";</script>'
    return http.HttpResponse(msg) 
开发者ID:elsigh,项目名称:browserscope,代码行数:22,代码来源:util.py

示例6: gh_admin_top

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def gh_admin_top():
  stars = util.param('stars', int) or 10000
  page = util.param('page', int) or 1
  per_page = util.param('per_page', int) or 100
  # TODO: fix formatting
  result = urlfetch.fetch('https://api.github.com/search/repositories?q=stars:>=%s&sort=stars&order=asc&page=%d&per_page=%d' % (stars, page, per_page))
  if result.status_code == 200:
    repos = json.loads(result.content)
  else:
    flask.abort(result.status_code)

  for repo in repos['items']:
    account = repo['owner']
    account_db = model.Account.get_or_insert(
      account['login'],
      avatar_url=account['avatar_url'].split('?')[0],
      email=account['email'] if 'email' in account else '',
      name=account['login'],
      followers=account['followers'] if 'followers' in account else 0,
      organization=account['type'] == 'Organization',
      username=account['login'],
    )

  return 'OK %d of %d' % (len(repos['items']), repos['total_count']) 
开发者ID:lipis,项目名称:github-stats,代码行数:26,代码来源:gh.py

示例7: request

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def request(self, method, url, headers, post_data=None):
        try:
            result = urlfetch.fetch(
                url=url,
                method=method,
                headers=headers,
                # Google App Engine doesn't let us specify our own cert bundle.
                # However, that's ok because the CA bundle they use recognizes
                # api.stripe.com.
                validate_certificate=self._verify_ssl_certs,
                # GAE requests time out after 60 seconds, so make sure we leave
                # some time for the application to handle a slow Stripe
                deadline=55,
                payload=post_data
            )
        except urlfetch.Error, e:
            self._handle_request_error(e, url) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:19,代码来源:http_client.py

示例8: _handle_request_error

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def _handle_request_error(self, e, url):
        if isinstance(e, urlfetch.InvalidURLError):
            msg = ("The Stripe library attempted to fetch an "
                   "invalid URL (%r). This is likely due to a bug "
                   "in the Stripe Python bindings. Please let us know "
                   "at support@stripe.com." % (url,))
        elif isinstance(e, urlfetch.DownloadError):
            msg = "There was a problem retrieving data from Stripe."
        elif isinstance(e, urlfetch.ResponseTooLargeError):
            msg = ("There was a problem receiving all of your data from "
                   "Stripe.  This is likely due to a bug in Stripe. "
                   "Please let us know at support@stripe.com.")
        else:
            msg = ("Unexpected error communicating with Stripe. If this "
                   "problem persists, let us know at support@stripe.com.")

        msg = textwrap.fill(msg) + "\n\n(Network error: " + str(e) + ")"
        raise error.APIConnectionError(msg) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:20,代码来源:http_client.py

示例9: send_request

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def send_request(fields):
    config = model.Config.get()

    fields["VERSION"] = "113"
    fields["USER"] =  config.paypal_user
    fields["PWD"] =  config.paypal_password
    fields["SIGNATURE"] = config.paypal_signature

    form_data = urllib.urlencode(fields)

    result = urlfetch.fetch(url=config.paypal_api_url, payload=form_data, method=urlfetch.POST,
                headers={'Content-Type': 'application/x-www-form-urlencoded'})
    result_map = urlparse.parse_qs(result.content)

    if 'ACK' in result_map:
        if result_map['ACK'][0] == "Success":
            return (True, result_map)
   
        logging.warning("Paypal returned an error:")
        logging.warning(pprint.pformat(result_map))
        return (False, result_map)

    logging.warning("Could not contact Paypal:")
    logging.warning(result.content)
    return False, result.content 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:27,代码来源:paypal.py

示例10: get

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def get(self):
    util.EnableCors(self)

    WP_PLEDGES = 4099
    VERSION_12_AND_UNDER = 59009 

    count = memcache.get('TOTAL-PLEDGES')
    if not count:
      query = model.Pledge.all(keys_only=True).filter('model_version >', 12)
      i = 0
      while True:
          result = query.fetch(1000)
          i = i + len(result)
          if len(result) < 1000:
              break
          cursor = query.cursor()
          query.with_cursor(cursor)
      count = i + WP_PLEDGES + VERSION_12_AND_UNDER
      memcache.set('TOTAL-PLEDGES', count, 120)

    self.response.headers['Content-Type'] = 'application/json'
    json.dump({'count':count}, self.response) 
开发者ID:MayOneUS,项目名称:pledgeservice,代码行数:24,代码来源:handlers.py

示例11: push_important_news

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def push_important_news():
    key = request.values.get('key')
    news = ndb.Key(urlsafe=key).get()
    form_fields = {
        "token": app.config["PUSHOVER_APP_KEY"],
        "user": app.config["PUSHOVER_USER_KEY"],
        "message": news.summary.encode("utf-8"),
        "url": news.link.encode("utf-8"),
        "url_title": u"点击访问正文".encode("utf-8"),
        "title": news.title.encode("utf-8"),
    }
    form_data = urllib.urlencode(form_fields)
    urlfetch.fetch(url=app.config["PUSH_OVER_URL"],
                   payload=form_data,
                   method=urlfetch.POST,
                   headers={'Content-Type': 'application/x-www-form-urlencoded'},
                   follow_redirects=False,
                   validate_certificate=False)
    return "Done", 200 
开发者ID:liantian-cn,项目名称:RSSNewsGAE,代码行数:21,代码来源:background.py

示例12: request

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def request(self, method, url, headers, post_data=None):
        try:
            result = urlfetch.fetch(
                url=url,
                method=method,
                headers=headers,
                # Google App Engine doesn't let us specify our own cert bundle.
                # However, that's ok because the CA bundle they use recognizes
                # api.goshippo.com.
                validate_certificate=self._verify_ssl_certs,
                # GAE requests time out after 60 seconds, so make sure we leave
                # some time for the application to handle a slow Shippo
                deadline=55,
                payload=post_data
            )
        except urlfetch.Error as e:
            self._handle_request_error(e, url)

        return result.content, result.status_code 
开发者ID:goshippo,项目名称:shippo-python-client,代码行数:21,代码来源:http_client.py

示例13: _handle_request_error

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def _handle_request_error(self, e, url):
        if isinstance(e, urlfetch.InvalidURLError):
            msg = ("The Shippo library attempted to fetch an "
                   "invalid URL (%r). This is likely due to a bug "
                   "in the Shippo Python bindings. Please let us know "
                   "at support@goshippo.com." % (url,))
        elif isinstance(e, urlfetch.DownloadError):
            msg = "There was a problem retrieving data from Shippo."
        elif isinstance(e, urlfetch.ResponseTooLargeError):
            msg = ("There was a problem receiving all of your data from "
                   "Shippo.  This is likely due to a bug in Shippo. "
                   "Please let us know at support@goshippo.com.")
        else:
            msg = ("Unexpected error communicating with Shippo. If this "
                   "problem persists, let us know at support@goshippo.com.")

        msg = textwrap.fill(msg) + "\n\n(Network error: " + str(e) + ")"
        raise error.APIConnectionError(msg) 
开发者ID:goshippo,项目名称:shippo-python-client,代码行数:20,代码来源:http_client.py

示例14: get_file_info

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def get_file_info(self, access_token, name):

		headers = {
			'Content-Type' : 'application/json',
			'Authorization' : 'Bearer ' + access_token
		}

		data = {
    		"path": "/" + name,
		    "include_media_info": False,
		    "include_deleted": False,
		    "include_has_explicit_shared_members": False
		}

		result = urlfetch.fetch(
			payload=json.dumps(data),
			method=urlfetch.POST,
			url='https://api.dropboxapi.com/2/files/get_metadata',
			headers=headers
		)

		if result.status_code != 200:
			raise Exception("Failed to get file metadata from Dropbox. Status: %s, body: %s" % (result.status_code, result.content))
		self.log(result.content)
		return json.loads(result.content) 
开发者ID:einaregilsson,项目名称:MyLife,代码行数:27,代码来源:dropbox.py

示例15: get

# 需要导入模块: from google.appengine.api import urlfetch [as 别名]
# 或者: from google.appengine.api.urlfetch import fetch [as 别名]
def get(self):
        auth_token, _ = app_identity.get_access_token(
            'https://www.googleapis.com/auth/cloud-platform')
        logging.info(
            'Using token {} to represent identity {}'.format(
                auth_token, app_identity.get_service_account_name()))

        response = urlfetch.fetch(
            'https://www.googleapis.com/storage/v1/b?project={}'.format(
                app_identity.get_application_id()),
            method=urlfetch.GET,
            headers={
                'Authorization': 'Bearer {}'.format(auth_token)
            }
        )

        if response.status_code != 200:
            raise Exception(
                'Call failed. Status code {}. Body {}'.format(
                    response.status_code, response.content))

        result = json.loads(response.content)
        self.response.headers['Content-Type'] = 'application/json'
        self.response.write(json.dumps(result, indent=2)) 
开发者ID:GoogleCloudPlatform,项目名称:python-docs-samples,代码行数:26,代码来源:main.py


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