My requirement is to download an abc.zip file from some website http://clientdownload.xyz.com/Documents/abc.zip
For this activity I have written a python script as follows:
url_to_check = 'http://clientdownload.xyz.com/Documents/abc.zip'
username = "user"
password = "pwd"
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url_to_check, username, password)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
zip_file = urllib2.urlopen(url_to_check).read()
file_name = 'somefile.zip'
meta = zip_file.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
with open(file_name, 'wb') as dwn_file:
dwn_file.write(zip_file.read())
Whereas I am getting the following errors when I run the script:
File «updateCheck.py», line 68, in check_update
zip_file = urllib2.urlopen(url_to_check).read() File «/usr/lib/python2.7/urllib2.py», line 126, in urlopen
return _opener.open(url, data, timeout) File «/usr/lib/python2.7/urllib2.py», line 406, in open
response = meth(req, response) File «/usr/lib/python2.7/urllib2.py», line 519, in http_response
‘http’, request, response, code, msg, hdrs) File «/usr/lib/python2.7/urllib2.py», line 444, in error
return self._call_chain(*args) File «/usr/lib/python2.7/urllib2.py», line 378, in _call_chain
result = func(*args) File «/usr/lib/python2.7/urllib2.py», line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized
I have given the user name and password properly but it throws unauthorized error.
When I tried to download it using wget link with -http-user and --ask-password
options, I am able to download the file.
Also using the same script I am able to download files from other servers properly.
I ran this script to get more info:
import urllib2, re, time, sys
theurl='http://clientdownload.xxx.com/Documents/Forms/AllItems.aspx'
req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
if hasattr(e, 'code'):
if e.code != 401:
print 'We got another error'
print e.code
else:
print e.headers
print e.headers['www-authenticate']
I got the following information:
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
SPRequestGuid: 939bad00-40b7-49b9-bbbc-99d0267a1004
X-SharePointHealthScore: 0
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 14.0.0.6029
Date: Wed, 12 Feb 2014 13:14:19 GMT
Connection: close
Content-Length: 16
NTLM
I was trying to load a web page, but I ran into this problem. I do have the username and password, but I don’t know how to use them in python code. I looked up on python tutorial, and this is what I wrote:
import urllib2
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
username = 'user'
password = 'pass'
top_level_url = "www.something.com:80"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
opener.open('http://www.something.com/h/h.html')
urllib2.install_opener(opener)
response = urllib2.urlopen()
page = response.read()
print page
Anything wrong?
Rup
33.3k9 gold badges87 silver badges110 bronze badges
asked Apr 17, 2012 at 17:18
Here is working code
import urllib2
url = 'http://www.abc.com/index.html'
username = 'user'
password = 'pass'
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
page = urllib2.urlopen(url).read()
answered Jun 22, 2012 at 18:48
bigbig
1,8267 gold badges26 silver badges47 bronze badges
I think you can use the requests
module which would make it easier for you.
import requests
username = 'user'
password = 'pass'
url = 'http://www.example.com/index.html'
r = requests.get(url, auth=(username, password))
page = r.content
print page
answered Jul 18, 2014 at 0:19
Lerner ZhangLerner Zhang
5,8202 gold badges44 silver badges61 bronze badges
1
My requirement is to download an abc.zip file from some website http://clientdownload.xyz.com/Documents/abc.zip
For this activity I have written a python script as follows:
url_to_check = 'http://clientdownload.xyz.com/Documents/abc.zip'
username = "user"
password = "pwd"
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url_to_check, username, password)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
zip_file = urllib2.urlopen(url_to_check).read()
file_name = 'somefile.zip'
meta = zip_file.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
with open(file_name, 'wb') as dwn_file:
dwn_file.write(zip_file.read())
Whereas I am getting the following errors when I run the script:
File «updateCheck.py», line 68, in check_update
zip_file = urllib2.urlopen(url_to_check).read() File «/usr/lib/python2.7/urllib2.py», line 126, in urlopen
return _opener.open(url, data, timeout) File «/usr/lib/python2.7/urllib2.py», line 406, in open
response = meth(req, response) File «/usr/lib/python2.7/urllib2.py», line 519, in http_response
‘http’, request, response, code, msg, hdrs) File «/usr/lib/python2.7/urllib2.py», line 444, in error
return self._call_chain(*args) File «/usr/lib/python2.7/urllib2.py», line 378, in _call_chain
result = func(*args) File «/usr/lib/python2.7/urllib2.py», line 527, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 401: Unauthorized
I have given the user name and password properly but it throws unauthorized error.
When I tried to download it using wget link with -http-user and --ask-password
options, I am able to download the file.
Also using the same script I am able to download files from other servers properly.
I ran this script to get more info:
import urllib2, re, time, sys
theurl='http://clientdownload.xxx.com/Documents/Forms/AllItems.aspx'
req = urllib2.Request(theurl)
try:
handle = urllib2.urlopen(req)
except IOError, e:
if hasattr(e, 'code'):
if e.code != 401:
print 'We got another error'
print e.code
else:
print e.headers
print e.headers['www-authenticate']
I got the following information:
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
SPRequestGuid: 939bad00-40b7-49b9-bbbc-99d0267a1004
X-SharePointHealthScore: 0
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 14.0.0.6029
Date: Wed, 12 Feb 2014 13:14:19 GMT
Connection: close
Content-Length: 16
NTLM
getting this error as basic first app to connect to weather
py code
from flask import Flask, render_template, request
# import json to load JSON data to a python dictionary
import json
# urllib.request to make a request to api
import urllib.request
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def weather():
if request.method == 'POST':
city = request.form['city']
else:
# for default name mathura
city = 'mathura'
# your API key will come here
api = '74cbba5bab81bf66874f686f4d6232bd'
# source contain json data from api
source = urllib.request.urlopen(
http: // api.openweathermap.org / data / 2.5 / forecast?id = 524901 & APPID = {74cbba5bab81bf66874f686f4d6232bd}
# converting JSON data to a dictionary
list_of_data = json.loads(source)
# data for variable list_of_data
data = {
"country_code": str(list_of_data['sys']['country']),
"coordinate": str(list_of_data['coord']['lon']) + ' '
+ str(list_of_data['coord']['lat']),
"temp": str(list_of_data['main']['temp']) + 'k',
"pressure": str(list_of_data['main']['pressure']),
"humidity": str(list_of_data['main']['humidity']),
}
print(data)
return render_template('index.html', data=data)
if __name__ == '__main__':
app.run(debug=True)
html;
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>weather</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<nav class="row" style="background: #337ab7; color: white;">
<h1 class="col-md-3 text-center">weather</h1>
</nav>
<br />
<br />
<center class="row">
<form method="post" class="col-md-6 col-md-offset-3">
<div class="input-group">
<input type="text" class="form-control" name="city" placeholder="Search">
<div class="input-group-btn">
<button class="btn btn-primary" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
<form>
</center>
<div class="row">
{% if data.country_code and data.coordinate and data.temp and data.pressure and data.humidity %}
<div class="col-md-6 col-md-offset-3">
<h3>country code : {{data.country_code}}</h1>
<h5>coordinate : {{data.coordinate}}</h5>
<h5>temp : {{data.temp}}</h5>
<h5>pressure : {{data.pressure}} </h5>
<h5>humidity : {{data.humidity}}</h5>
</div>
{% endif %}
</div>
</body>
</html>
not sure gonna search it now but taking so lnog to find working tut
#lambda #python-3.8
Вопрос:
Я вызываю общедоступный API с поддержкой OAuth 2.0 в Python 3.8, чтобы сохранить ответ json в AWS-S3 с помощью функции AWS Lambda. Я сталкиваюсь с ошибкой HTTP Ошибка 401: Несанкционированный.
Функция(fnGetToken), которая получает токен, работает, и я могу успешно использовать токен в Postman и получить ответ. Код прерывается в функции fnGetFeed с сообщением об ошибке, показанным ниже. Я думаю, что urllib.request.urlopen(req) вызывает, но я думаю, что это стандартно. Я не эксперт по python и поэтому прошу экспертов поделиться своими отзывами, чтобы решить эту проблему.
import json
import base64
import urllib.request
import os
import boto3
def fnGetToken():
url = os.environ['authurl']
headers = {}
key = os.environ['okey']
secret = os.environ['osecret']
# auth header will be combination of client id, secret with 'Basic' Auth Header
authHeader = 'Basic ' str(base64.b64encode(bytes((key ':' secret), 'utf-8')), "utf-8")
print(authHeader)
headers['Authorization'] = authHeader
headers['ContentType'] = 'application/x-www-form-urlencoded;charset=UTF-8'
data = "grant_type=client_credentials"
req = urllib.request.Request(url, headers = headers, method = 'POST')
response = urllib.request.urlopen(req, data.encode('utf-8'))
respData = response.read()
data = json.loads(respData)
return data['access_token']
def fnGetFeed(token):
screenname = os.environ['screenname']
url = str(os.environ['apiurl']) screenname
print("url generated {}".format(url))
headers = {}
authHeader = 'bearer ' token
print("token passed: ".format(authHeader))
headers['Authorization'] = authHeader
req = urllib.request.Request(url, headers = headers, method = 'GET')
response = urllib.request.urlopen(req)
respData = response.read()
data = json.loads(respData)
return data
def lambda_handler(event, context):
token = fnGetToken()
print ("Token generated successfully {}".format(token))
data = fnGetFeed(token)
print ("response from get feed function {}".format(data))
{
"errorMessage": "HTTP Error 401: Unauthorized",
"errorType": "HTTPError",
"stackTrace": [
" File "/var/task/lambda_function.py", line 58, in lambda_handlern data = fnGetFeed(token)n",
" File "/var/task/lambda_function.py", line 42, in fnGetFeedn response = urllib.request.urlopen(req)n",
" File "/var/lang/lib/python3.8/urllib/request.py", line 222, in urlopenn return opener.open(url, data, timeout)n",
" File "/var/lang/lib/python3.8/urllib/request.py", line 531, in openn response = meth(req, response)n",
" File "/var/lang/lib/python3.8/urllib/request.py", line 640, in http_responsen response = self.parent.error(n",
" File "/var/lang/lib/python3.8/urllib/request.py", line 569, in errorn return self._call_chain(*args)n",
" File "/var/lang/lib/python3.8/urllib/request.py", line 502, in _call_chainn result = func(*args)n",
" File "/var/lang/lib/python3.8/urllib/request.py", line 649, in http_error_defaultn raise HTTPError(req.full_url, code, msg, hdrs, fp)n"
]
}
Спасибо!
Posts: 46
Joined: Mar 2013
Reputation:
1
2014-04-30, 11:56
(This post was last modified: 2014-05-05, 15:35 by silmano.)
I’m starting to mess a little with JSON-RPC API, but I don’t seem able to run any command. I’ve tried using curl with JSONRPC.Ping method, but it just executes it without any output and if I call the same method via Python script, I get a HTTP Error 401: Unauthorized.
I’ve checked that XBMC has two ports open: 7777 (I use this one for the Android remote) and 9090. If I use the 7777 port, I get an answer right away using both curl and python. With curl I just get my prompt back (with no answer nor error) and with python I get a 401 error. If I use port 9090, the program just stays there as XBMC doesn’t seem to answer from that port.
I’ve checked XBMC options and the only one not enabled is the UPnP protocol, the others to let other computers/programs handle XBMC are enabled. The Android remote app works without issue.
Any idea where could be the issue?
Posts: 5,184
Joined: Jan 2009
Reputation:
130
First of all you need to tell us what version of XBMC you are using. Then you need to provide a Debug log (wiki) from when you are trying to do the JSON-RPC requests. If you are using a Gotham Beta or RC you need to enable JSON-RPC logging in System -> Settings -> System -> Debugging. Last but not least you should provide the code snippet (or command) that you are executing to send the JSON-RPC request (including the exact JSON-RPC request).
HTTP 401 could mean that you have specified a username and password for XBMC’s webserver in which case you need to provide them with your HTTP requests.
Port 9090 is a TCP server so you won’t be able to send HTTP requests to it.
Always read the online manual (wiki), FAQ (wiki) and search the forum before posting.
Do not e-mail Team Kodi members directly asking for support. Read/follow the forum rules (wiki).
Please read the pages on troubleshooting (wiki) and bug reporting (wiki) before reporting issues.
Posts: 46
Joined: Mar 2013
Reputation:
1
2014-05-05, 11:14
(This post was last modified: 2014-05-05, 15:42 by silmano.)
I’m using XBMC version 12.3 (its on my signature). I think I was using a wrong username/password combination when using curl, so I’ve configured both again in XBMC and at least curl seems to be working:
Code:
$ curl --data-binary '{ "jsonrpc": "2.0", "method": "JSONRPC.Ping", "id": 1}' -H 'content-type: application/json;' http://<user>:<pass>@192.168.1.120:7777/jsonrpc
{"id":1,"jsonrpc":"2.0","result":"pong"}
In my case the problem isn’t from XBMC itself, so I don’t think a debug log would help us much. In this case the problem I’m facing is identifying myself via Python to be able to execute JSON-RPC from within the Python script itself.
Right now this is the code I’m testing against XBMC:
Code:
#!/usr/bin/env python3
import json
from urllib.request import Request, urlopen
headers = { 'Content-Type': 'application/json' }
url = 'http://192.168.1.120:7777/jsonrpc'
data = { "jsonrpc": "2.0", "method": "JSONRPC.Ping", "id": 1}
json_data = json.dumps(data)
post_data = json_data.encode('utf-8')
request = Request(url, post_data, headers)
result = urlopen(request)
print(result)
Executing this code I get the following error: urllib.error.HTTPError: HTTP Error 401: Unauthorized, mainly due to not using a username and password withing the Python script. Since Python doesn’t like an url like «http://<user>:<pass>@IP:port/», how can I send the user/pass information to XBMC? Will it accept an Authorization header?
EDIT: I’ve checked and XBMC accepts basic authentication with the Authorization header, so adding the header to the Request fixes the call and makes the script work as intended. This is the resulting code:
Code:
#!/usr/bin/env python3
import json
import base64
from urllib.request import Request, urlopen
credentials = b'user:pass'
encoded_credentials = base64.b64encode(credentials)
authorization = b'Basic ' + encoded_credentials
headers = { 'Content-Type': 'application/json', 'Authorization': authorization }
url = 'http://192.168.1.120:7777/jsonrpc'
data = { "jsonrpc": "2.0", "method": "JSONRPC.Ping", "id": 1}
json_data = json.dumps(data)
post_data = json_data.encode('utf-8')
request = Request(url, post_data, headers)
result = urlopen(request)
print(result.read())
КАК получить интернет-ресурсы с помощью пакета urllib
- Author
-
Michael Foord
Introduction
urllib.request — это модуль Python для получения URL-адресов (унифицированных указателей ресурсов). Он предлагает очень простой интерфейс в виде функции urlopen . Это позволяет получать URL-адреса с использованием множества различных протоколов. Он также предлагает немного более сложный интерфейс для обработки распространенных ситуаций, таких как базовая аутентификация, файлы cookie, прокси и т. Д. Они предоставляются объектами, называемыми обработчиками и открывателями.
urllib.request поддерживает выборку URL-адресов для многих «схем URL-адресов» (обозначается строкой перед ":"
в URL-адресе — например , "ftp"
— это схема URL-адресов "ftp://python.org/"
), используя связанную с ними сеть . протоколы (например, FTP, HTTP). В этом руководстве рассматривается наиболее распространенный случай — HTTP.
Для простых ситуаций urlopen очень прост в использовании. Но как только вы столкнетесь с ошибками или нетривиальными случаями при открытии URL-адресов HTTP, вам потребуется некоторое понимание протокола передачи гипертекста. Наиболее полной и авторитетной ссылкой на HTTP является RFC 2616 . Это технический документ, и он не предназначен для легкого чтения. Этот HOWTO призван проиллюстрировать использование urllib с достаточным количеством подробностей о HTTP, чтобы помочь вам в этом. Он не предназначен для замены документов urllib.request
, но дополняет их.
Fetching URLs
Самый простой способ использования urllib.request заключается в следующем:
import urllib.request with urllib.request.urlopen('http://python.org/') as response: html = response.read()
Если вы хотите получить ресурс по URL-адресу и сохранить его во временном месте, вы можете сделать это с помощью функций shutil.copyfileobj()
и tempfile.NamedTemporaryFile()
:
import shutil import tempfile import urllib.request with urllib.request.urlopen('http://python.org/') as response: with tempfile.NamedTemporaryFile(delete=False) as tmp_file: shutil.copyfileobj(response, tmp_file) with open(tmp_file.name) as html: pass
Многие случаи использования urllib будут настолько простыми (обратите внимание,что вместо URL ‘http:’ мы могли бы использовать URL,начинающийся с ‘ftp:’,’file:’ и т.д.).Однако цель этого руководства-объяснить более сложные случаи,сосредоточившись на HTTP.
HTTP основан на запросах и ответах — клиент делает запросы, а серверы отправляют ответы. urllib.request отражает это с помощью объекта Request
, который представляет собой HTTP-запрос, который вы делаете. В простейшей форме вы создаете объект Request, который указывает URL-адрес, который вы хотите получить. Вызов urlopen
с этим объектом Request возвращает объект ответа для запрошенного URL. Этот ответ представляет собой объект в виде файла, что означает, что вы можете, например, вызвать .read()
для ответа:
import urllib.request req = urllib.request.Request('http://www.voidspace.org.uk') with urllib.request.urlopen(req) as response: the_page = response.read()
Обратите внимание,что urllib.request использует один и тот же интерфейс Request для работы со всеми схемами URL.Например,вы можете сделать FTP-запрос следующим образом:
req = urllib.request.Request('ftp://example.com/')
В случае HTTP есть две дополнительные вещи, которые позволяют вам делать объекты Request: во-первых, вы можете передавать данные для отправки на сервер. Во- вторых, вы можете передать дополнительную информацию («метаданные») о данных или о самом запросе на сервер — эта информация отправляется в виде «заголовков» HTTP. Давайте рассмотрим каждый из них по очереди.
Data
Иногда вы хотите отправить данные по URL-адресу (часто URL-адрес будет ссылаться на сценарий CGI (общий интерфейс шлюза) или другое веб-приложение). В HTTP это часто делается с помощью так называемого POST — запроса. Это часто то, что делает ваш браузер, когда вы отправляете HTML-форму, которую вы заполнили в Интернете. Не все POST должны исходить из форм: вы можете использовать POST для передачи произвольных данных в ваше собственное приложение. В общем случае HTML-форм данные должны быть закодированы стандартным способом, а затем переданы объекту запроса в качестве аргумента data
Кодирование выполняется с помощью функции из библиотеки urllib.parse
.
import urllib.parse import urllib.request url = 'http://www.someserver.com/cgi-bin/register.cgi' values = {'name' : 'Michael Foord', 'location' : 'Northampton', 'language' : 'Python' } data = urllib.parse.urlencode(values) data = data.encode('ascii') # data should be bytes req = urllib.request.Request(url, data) with urllib.request.urlopen(req) as response: the_page = response.read()
Обратите внимание, что иногда требуются другие кодировки (например, для загрузки файлов из HTML-форм — см. Спецификацию HTML, Отправка форм для более подробной информации).
Если вы не передаете аргумент data
, urllib использует запрос GET . Одно из отличий GET- и POST-запросов заключается в том, что POST-запросы часто имеют «побочные эффекты»: они каким-то образом изменяют состояние системы (например, размещая на веб-сайте заказ на доставку центнера консервированного спама). до твоей двери). Хотя стандарт HTTP ясно дает понять, что POST -запросы всегда вызывают побочные эффекты, а GET-запросы никогда не вызывают побочных эффектов, ничто не мешает GET-запросу иметь побочные эффекты, а POST-запросы не иметь побочных эффектов. Данные также можно передавать в HTTP-запросе GET, кодируя их в самом URL-адресе.
Это делается следующим образом:
>>> import urllib.request >>> import urllib.parse >>> data = {} >>> data['name'] = 'Somebody Here' >>> data['location'] = 'Northampton' >>> data['language'] = 'Python' >>> url_values = urllib.parse.urlencode(data) >>> print(url_values) name=Somebody+Here&language=Python&location=Northampton >>> url = 'http://www.example.com/example.cgi' >>> full_url = url + '?' + url_values >>> data = urllib.request.urlopen(full_url)
Обратите внимание, что полный URL-адрес создается путем добавления символа ?
к URL-адресу, за которым следуют закодированные значения.
Handling Exceptions
urlopen вызывает URLError
, когда не может обработать ответ (хотя, как обычно с API Python, также могут возникать встроенные исключения, такие как ValueError
, TypeError
и т.д.).
HTTPError
— это подкласс URLError
, возникающий в конкретном случае URL-адресов HTTP.
Классы исключений экспортируются из модуля urllib.error
.
URLError
Часто URLError возникает из-за отсутствия сетевого соединения (нет маршрута к указанному серверу),или указанный сервер не существует.В этом случае вызванное исключение будет иметь атрибут ‘reason’,который представляет собой кортеж,содержащий код ошибки и текстовое сообщение об ошибке.
e.g.
>>> req = urllib.request.Request('http://www.pretend_server.org') >>> try: urllib.request.urlopen(req) ... except urllib.error.URLError as e: ... print(e.reason) ... (4, 'getaddrinfo failed')
HTTPError
Каждый HTTP-ответ от сервера содержит числовой «код состояния». Иногда код состояния указывает на то, что сервер не может выполнить запрос. Обработчики по умолчанию будут обрабатывать некоторые из этих ответов за вас (например, если ответ представляет собой «перенаправление», запрашивающее у клиента получение документа с другого URL-адреса, urllib обработает это за вас). Для тех, с которыми он не может справиться, urlopen вызовет HTTPError
. Типичные ошибки включают «404» (страница не найдена), «403» (запрос запрещен) и «401» (требуется аутентификация).
См. раздел 10 RFC 2616 для справки по всем кодам ошибок HTTP.
HTTPError
будет иметь целочисленный атрибут «код», который соответствует ошибке, отправленной сервером.
Error Codes
Поскольку обработчики по умолчанию обрабатывают перенаправления (коды в диапазоне 300),а коды в диапазоне 100-299 означают успех,вы обычно будете видеть только коды ошибок в диапазоне 400-599.
http.server.BaseHTTPRequestHandler.responses
— это полезный словарь кодов ответов, в котором показаны все коды ответов, используемые RFC 2616 . Словарь воспроизведен здесь для удобства
# Table mapping response codes to messages; entries have the # form {code: (shortmessage, longmessage)}. responses = { 100: ('Continue', 'Request received, please continue'), 101: ('Switching Protocols', 'Switching to new protocol; obey Upgrade header'), 200: ('OK', 'Request fulfilled, document follows'), 201: ('Created', 'Document created, URL follows'), 202: ('Accepted', 'Request accepted, processing continues off-line'), 203: ('Non-Authoritative Information', 'Request fulfilled from cache'), 204: ('No Content', 'Request fulfilled, nothing follows'), 205: ('Reset Content', 'Clear input form for further input.'), 206: ('Partial Content', 'Partial content follows.'), 300: ('Multiple Choices', 'Object has several resources -- see URI list'), 301: ('Moved Permanently', 'Object moved permanently -- see URI list'), 302: ('Found', 'Object moved temporarily -- see URI list'), 303: ('See Other', 'Object moved -- see Method and URL list'), 304: ('Not Modified', 'Document has not changed since given time'), 305: ('Use Proxy', 'You must use proxy specified in Location to access this ' 'resource.'), 307: ('Temporary Redirect', 'Object moved temporarily -- see URI list'), 400: ('Bad Request', 'Bad request syntax or unsupported method'), 401: ('Unauthorized', 'No permission -- see authorization schemes'), 402: ('Payment Required', 'No payment -- see charging schemes'), 403: ('Forbidden', 'Request forbidden -- authorization will not help'), 404: ('Not Found', 'Nothing matches the given URI'), 405: ('Method Not Allowed', 'Specified method is invalid for this server.'), 406: ('Not Acceptable', 'URI not available in preferred format.'), 407: ('Proxy Authentication Required', 'You must authenticate with ' 'this proxy before proceeding.'), 408: ('Request Timeout', 'Request timed out; try again later.'), 409: ('Conflict', 'Request conflict.'), 410: ('Gone', 'URI no longer exists and has been permanently removed.'), 411: ('Length Required', 'Client must specify Content-Length.'), 412: ('Precondition Failed', 'Precondition in headers is false.'), 413: ('Request Entity Too Large', 'Entity is too large.'), 414: ('Request-URI Too Long', 'URI is too long.'), 415: ('Unsupported Media Type', 'Entity body in unsupported format.'), 416: ('Requested Range Not Satisfiable', 'Cannot satisfy request range.'), 417: ('Expectation Failed', 'Expect condition could not be satisfied.'), 500: ('Internal Server Error', 'Server got itself in trouble'), 501: ('Not Implemented', 'Server does not support this operation'), 502: ('Bad Gateway', 'Invalid responses from another server/proxy.'), 503: ('Service Unavailable', 'The server cannot process the request due to a high load'), 504: ('Gateway Timeout', 'The gateway server did not receive a timely response'), 505: ('HTTP Version Not Supported', 'Cannot fulfill request.'), }
Когда возникает ошибка, сервер отвечает, возвращая код ошибки HTTP и страницу с ошибкой. Вы можете использовать экземпляр HTTPError
в качестве ответа на возвращенной странице. Это означает, что, помимо атрибута code, он также имеет методы read, geturl и info, возвращаемые модулем urllib.response
:
>>> req = urllib.request.Request('http://www.python.org/fish.html')
>>> try:
... urllib.request.urlopen(req)
... except urllib.error.HTTPError as e:
... print(e.code)
... print(e.read())
...
404
b'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">nnn<html
...
<title>Page Not Found</title>n
...
© 2001–2022 Python Software Foundation
Licensed under the PSF License.
https://docs.python.org/3.11/howto/urllib2.html
Python
3.11
-
Unicode HOWTO
1.12 В этом HOWTO рассматривается поддержка Python спецификации Unicode,представляющей текстовые данные,и объясняются различные проблемы,которые обычно возникают у людей.
-
Преобразование в байты
Противоположным методом bytes.decode()является str.encode(),который возвращает строку представления Unicode,закодированную запрошенной кодировкой.
-
Подведение итогов
Поэтому,если вы хотите быть готовым к HTTPError URLError,есть два основных подхода.
-
Установка питоновых модулей (версия Legacy)
Greg Ward Примечание Весь пакет distutils был устаревшим и будет удален в Python 3.12.
My public app is developed with Python API and uses Flask.
It successfully installs and I get and keep an offline access_token in my database with the scope [«write_products», «read_products», «read_script_tags», «write_script_tags»].
Now I want to use my new-found authenticated session to actually do something useful! The first order of business is inserting a script_tag on the customer’s shop.
So I do the following:
def upsert_script_tag(self, src): script_reference={"event": "onload", "src": f"{src}"} print(f"UPSERTING SCRIPT TAG WITH '{script_reference}'") st=shopify.ScriptTag(script_reference) ret = st.save() if st.errors: print(f"ERROR: {st.errors.full_messages()}") print(f" + Return was :{ret}")
At which point I get the following in my log when it gets called:
UPSERTING SCRIPT TAG WITH '{'event': 'onload', 'src': 'https://bsp.this-some-whaky-site.com/shopify/script_tag'}' shopify_app | Traceback (most recent call last): shopify_app | File "/usr/local/lib/python3.7/site-packages/pyactiveresource/connection.py", line 286, in _open shopify_app | http_response = self._handle_error(self._urlopen(request)) shopify_app | File "/usr/local/lib/python3.7/site-packages/pyactiveresource/connection.py", line 316, in _urlopen shopify_app | return urllib.request.urlopen(request, timeout=self.timeout) shopify_app | File "/usr/local/lib/python3.7/urllib/request.py", line 222, in urlopen shopify_app | return opener.open(url, data, timeout) shopify_app | File "/usr/local/lib/python3.7/urllib/request.py", line 531, in open shopify_app | response = meth(req, response) shopify_app | File "/usr/local/lib/python3.7/urllib/request.py", line 641, in http_response shopify_app | 'http', request, response, code, msg, hdrs) shopify_app | File "/usr/local/lib/python3.7/urllib/request.py", line 569, in error shopify_app | return self._call_chain(*args) shopify_app | File "/usr/local/lib/python3.7/urllib/request.py", line 503, in _call_chain shopify_app | result = func(*args) shopify_app | File "/usr/local/lib/python3.7/urllib/request.py", line 649, in http_error_default shopify_app | raise HTTPError(req.full_url, code, msg, hdrs, fp) shopify_app | urllib.error.HTTPError: HTTP Error 401: Unauthorized shopify_app | shopify_app | During handling of the above exception, another exception occurred: shopify_app | shopify_app | Traceback (most recent call last): shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2463, in __call__ shopify_app | return self.wsgi_app(environ, start_response) shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2449, in wsgi_app shopify_app | response = self.handle_exception(e) shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1866, in handle_exception shopify_app | reraise(exc_type, exc_value, tb) shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise shopify_app | raise value shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 2446, in wsgi_app shopify_app | response = self.full_dispatch_request() shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1951, in full_dispatch_request shopify_app | rv = self.handle_user_exception(e) shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1820, in handle_user_exception shopify_app | reraise(exc_type, exc_value, tb) shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/_compat.py", line 39, in reraise shopify_app | raise value shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1949, in full_dispatch_request shopify_app | rv = self.dispatch_request() shopify_app | File "/usr/local/lib/python3.7/site-packages/flask/app.py", line 1935, in dispatch_request shopify_app | return self.view_functions[rule.endpoint](**req.view_args) shopify_app | File "./shopify_app/shopify_bp/decorators.py", line 51, in decorated_function shopify_app | return f(*args, **kwargs) shopify_app | File "./shopify_app/shopify_bp/views.py", line 196, in settings_post shopify_app | sm.upsert_script_tag(script_tag_url) shopify_app | File "./fk/api/shopify/Shopify.py", line 159, in upsert_script_tag shopify_app | script = st.save() shopify_app | File "/usr/local/lib/python3.7/site-packages/pyactiveresource/activeresource.py", line 824, in save shopify_app | data=self.encode()) shopify_app | File "/usr/local/lib/python3.7/site-packages/pyactiveresource/connection.py", line 364, in post shopify_app | return self._open('POST', path, headers=headers, data=data) shopify_app | File "/usr/local/lib/python3.7/site-packages/shopify/base.py", line 23, in _open shopify_app | self.response = super(ShopifyConnection, self)._open(*args, **kwargs) shopify_app | File "/usr/local/lib/python3.7/site-packages/pyactiveresource/connection.py", line 288, in _open shopify_app | http_response = self._handle_error(err) shopify_app | File "/usr/local/lib/python3.7/site-packages/pyactiveresource/connection.py", line 404, in _handle_error shopify_app | raise UnauthorizedAccess(err) shopify_app | pyactiveresource.connection.UnauthorizedAccess: Response(code=401, body="b'{"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}'", headers={'Date': 'Sun, 15 Sep 2019 22:17:42 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'close', 'Set-Cookie': '__cfduid=da23de8c***************0e609367701568585861; expires=Mon, 14-Sep-20 22:17:41 GMT; path=/; domain=.myshopify.com; HttpOnly', 'X-Sorting-Hat-PodId': '34', 'X-Sorting-Hat-ShopId': '5263130659', 'Referrer-Policy': 'origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'X-ShopId': '5263130659', 'X-ShardId': '34', 'WWW-Authenticate': 'Basic Realm="Shopify API Authentication"', 'Strict-Transport-Security': 'max-age=7889238', 'X-Request-Id': 'cfb8e7c***************c-740f4136eced', 'X-Shopify-Stage': 'production', 'Content-Security-Policy': "default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; frame-ancestors 'none'; img-src 'self' data: blob: https:; script-src https://cdn.shopify.com https://cdn.shopify.cn https://checkout.shopifycs.com https://js-agent.newrelic.com https://bam.nr-data.net https://dme0ih8comzn4.cloudfront.net https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://js.braintreegateway.com https://c.paypal.com https://maps.googleapis.com https://www.google-analytics.com https://v.shopify.com https://widget.intercom.io https://js.intercomcdn.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; report-uri /csp-report?source%5Baction%5D=create&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Fscript_tags&source%5Bsection%5D=admin_api&source%5Buuid%5D=cfb8e7c6-0c90-4507-a9bc-740f4136eced", 'X-Content-Type-Options': 'nosniff', 'X-Download-Options': 'noopen', 'X-Permitted-Cross-Domain-Policies': 'none', 'X-XSS-Protection': '1; mode=block; report=/xss-report?source%5Baction%5D=create&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Fscript_tags&source%5Bsection%5D=admin_api&source%5Buuid%5D=cfb8e7c***************c-740f4136eced', 'X-Dc': 'gcp-us-central1,gcp-us-central1', 'set-cookie': '__cfduid=da23de8c***************0e609367701568585861; expires=Mon, 14-Sep-20 22:17:41 GMT; path=/; domain=.myshopify.com; HttpOnly', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '51**********dfdf-FRA'}, msg="Unauthorized")
So how can I debug this? Is there some way I can get more information about why it was unauthorized?
https://www.merchbot.net