我使用web服务来检索一些数据,但有时网址不起作用,我的网站没有加载.你知道我如何处理以下异常,所以如果webservice不工作,网站没有问题吗?
Django Version: 1.3.1
Exception Type: ConnectionError
Exception Value:
HTTPConnectionPool(host='test.com', port=8580): Max retries exceeded with url:
Run Code Online (Sandbox Code Playgroud)
我用了
try:
r = requests.get("http://test.com", timeout=0.001)
except requests.exceptions.RequestException as e: # This is the correct syntax
print e
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
但没有任何反应
使用requestspython lib,我发出一个GET请求,并处理Timeout异常(以及我未在此处显示的其他异常),如
import requests
timeout1=20
timeout2=40
try:
#first attempt
resp = requests.get(base_url+resource, params=payload, headers=headers,
timeout=timeout1)
except requests.exceptions.Timeout:
#timed out, retry once
try:
resp = requests.get(base_url+resource, params=payload, headers=headers,
timeout=timeout2)
return resp.json()
except requests.exceptions.RequestException as e:
#Still failed; return error code
return -1
Run Code Online (Sandbox Code Playgroud)
这在大多数情况下工作正常,但有时我的程序只是完全退出错误socket.timeout: timed out,而不是抛出requests.exceptions.Timeout并被捕获和处理.
为什么请求lib的行为如此?我该怎么处理?
我正在使用Python请求库来实现重试逻辑。这是我制作的一个简单脚本,用于重现我遇到的问题。在重试用完的情况下,我希望能够至少记录服务器的响应之一以帮助调试。但是,我不清楚如何访问该信息。当然,我可以通过其他方式实现重试来实现我的目标,但是似乎这并不是一个极端的情况,而令我惊讶的是,发现请求不支持我的用例。
我已经看过了包装的requests.exceptions.RetryError,包装的requests.packages.urllib3.exceptions.MaxRetryError和包装都没有用的request.packages.urllib3.exceptions.ResponseError。
我想念什么吗?
#!/usr/bin/env python
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from requests.exceptions import RetryError
def main():
retry_policy = Retry(
total=3,
status_forcelist=[418])
session = requests.Session()
session.mount('http://', HTTPAdapter(max_retries=retry_policy))
try:
session.get('http://httpbin.org/status/418')
except RetryError as retry_error:
print retry_error
print retry_error.response is None
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
$ python test.py
HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /status/418 (Caused by ResponseError('too many 418 error responses',))
True
Run Code Online (Sandbox Code Playgroud) 需要在 python 中捕获 HTTP 错误的响应正文。当前使用 python 请求模块的 raise_for_status()。此方法仅返回状态代码和描述。需要一种方法来捕获详细错误日志的响应正文。
如果某些不同的模块中存在类似的必需功能,请建议 python requests 模块的替代方案。如果没有,请建议可以对现有代码进行哪些更改以捕获所述响应正文。
当前实现仅包含以下内容:
resp.raise_for_status()
Run Code Online (Sandbox Code Playgroud) 我的问题很简单.我有一个try/except代码.在尝试中我有一些http请求尝试,除了我有几种方法来处理我得到的异常.
现在我想在我的代码中添加一个时间参数.这意味着尝试只会持续'n'秒.否则接受它除外.
在自由语言中,它将显示为:
try for n seconds:
doSomthing()
except (after n seconds):
handleException()
Run Code Online (Sandbox Code Playgroud)
这是中码.不是功能.我必须抓住超时并处理它.我不能只是继续代码.
while (recoveryTimes > 0):
try (for 10 seconds):
urllib2.urlopen(req)
response = urllib2.urlopen(req)
the_page = response.read()
recoveryTimes = 0
except (urllib2.URLError, httplib.BadStatusLine) as e:
print str(e.__unicode__())
print sys.exc_info()[0]
recoveryTimes -= 1
if (recoveryTimes > 0):
print "Retrying request. Requests left %s" %recoveryTimes
continue
else:
print "Giving up request, changing proxy."
setUrllib2Proxy()
break
except (timedout, 10 seconds has passed)
setUrllib2Proxy()
break
Run Code Online (Sandbox Code Playgroud)
我需要的解决方案是try (for 10 seconds) …
我有以下烧瓶代码:
from flask import Flask,request,jsonify
import requests
from werkzeug.exceptions import InternalServerError, NotFound
import sys
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = "Secret!"
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
rv['status_code'] = self.status_code
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/test',methods=["GET","POST"])
def test():
url = "https://httpbin.org/status/404"
try: …Run Code Online (Sandbox Code Playgroud) 我是 Python 新手,所以遇到了一些麻烦。我正在尝试构建一个工具,通过代理将数据发布到外部服务器。我可以正常工作,但问题是我不知道如何捕获代理连接错误并打印其他内容。我写的代码是:
import requests
from bs4 import BeautifulSoup
headers = {
"User-Agent": "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11",
"Content-Type": "application/json"
}
proxies = {
"https": "https://244.324.324.32:8081",
}
data = {"test": "test"}
r = requests.post("https://example.com/page", proxies=proxies, json=data, headers=headers)
print(r.text)
Run Code Online (Sandbox Code Playgroud)
当代理已死(未连接/工作)或类似内容时,如何打印,例如“代理连接错误”。这是我第一次使用 python,所以我遇到了麻烦。
谢谢你
python ×6
connection ×1
flask ×1
proxy ×1
python-2.7 ×1
python-2.x ×1
timer ×1
try-catch ×1
url ×1