Python response. json hatası

Kamikaze21

Hectopat
Katılım
15 Ocak 2022
Mesajlar
25
Çözümler
1
Daha fazla  
Cinsiyet
Erkek
Kod:
gaierror                                  Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\urllib3\connection.py:199, in HTTPConnection._new_conn(self)
    198 try:
--> 199     sock = connection.create_connection(
    200         (self._dns_host, self.port),
    201         self.timeout,
    202         source_address=self.source_address,
    203         socket_options=self.socket_options,
    204     )
    205 except socket.gaierror as e:

File ~\anaconda3\Lib\site-packages\urllib3\util\connection.py:60, in create_connection(address, timeout, source_address, socket_options)
     58     raise LocationParseError(f"'{host}', label empty or too long") from None
---> 60 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
     61     af, socktype, proto, canonname, sa = res

File ~\anaconda3\Lib\socket.py:963, in getaddrinfo(host, port, family, type, proto, flags)
    962 addrlist = []
--> 963 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    964     af, socktype, proto, canonname, sa = res

gaierror: [Errno 11001] getaddrinfo failed

The above exception was the direct cause of the following exception:

NameResolutionError                       Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\urllib3\connectionpool.py:789, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
    788 # Make the request on the HTTPConnection object
--> 789 response = self._make_request(
    790     conn,
    791     method,
    792     url,
    793     timeout=timeout_obj,
    794     body=body,
    795     headers=headers,
    796     chunked=chunked,
    797     retries=retries,
    798     response_conn=response_conn,
    799     preload_content=preload_content,
    800     decode_content=decode_content,
    801     **response_kw,
    802 )
    804 # Everything went great!

File ~\anaconda3\Lib\site-packages\urllib3\connectionpool.py:490, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
    489         new_e = _wrap_proxy_error(new_e, conn.proxy.scheme)
--> 490     raise new_e
    492 # conn.request() calls http.client.*.request, not the method in
    493 # urllib3.request. It also calls makefile (recv) on the socket.

File ~\anaconda3\Lib\site-packages\urllib3\connectionpool.py:466, in HTTPConnectionPool._make_request(self, conn, method, url, body, headers, retries, timeout, chunked, response_conn, preload_content, decode_content, enforce_content_length)
    465 try:
--> 466     self._validate_conn(conn)
    467 except (SocketTimeout, BaseSSLError) as e:

File ~\anaconda3\Lib\site-packages\urllib3\connectionpool.py:1095, in HTTPSConnectionPool._validate_conn(self, conn)
   1094 if conn.is_closed:
-> 1095     conn.connect()
   1097 # TODO revise this, see https://github.com/urllib3/urllib3/issues/2791

File ~\anaconda3\Lib\site-packages\urllib3\connection.py:693, in HTTPSConnection.connect(self)
    692 sock: socket.socket | ssl.SSLSocket
--> 693 self.sock = sock = self._new_conn()
    694 server_hostname: str = self.host

File ~\anaconda3\Lib\site-packages\urllib3\connection.py:206, in HTTPConnection._new_conn(self)
    205 except socket.gaierror as e:
--> 206     raise NameResolutionError(self.host, self, e) from e
    207 except SocketTimeout as e:

NameResolutionError: <urllib3.connection.HTTPSConnection object at 0x0000019F56E62C30>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)

The above exception was the direct cause of the following exception:

MaxRetryError                             Traceback (most recent call last)
File ~\anaconda3\Lib\site-packages\requests\adapters.py:667, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
    666 try:
--> 667     resp = conn.urlopen(
    668         method=request.method,
    669         url=url,
    670         body=request.body,
    671         headers=request.headers,
    672         redirect=False,
    673         assert_same_host=False,
    674         preload_content=False,
    675         decode_content=False,
    676         retries=self.max_retries,
    677         timeout=timeout,
    678         chunked=chunked,
    679     )
    681 except (ProtocolError, OSError) as err:

File ~\anaconda3\Lib\site-packages\urllib3\connectionpool.py:843, in HTTPConnectionPool.urlopen(self, method, url, body, headers, retries, redirect, assert_same_host, timeout, pool_timeout, release_conn, chunked, body_pos, preload_content, decode_content, **response_kw)
    841     new_e = ProtocolError("Connection aborted.", new_e)
--> 843 retries = retries.increment(
    844     method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
    845 )
    846 retries.sleep()

File ~\anaconda3\Lib\site-packages\urllib3\util\retry.py:519, in Retry.increment(self, method, url, response, error, _pool, _stacktrace)
    518     reason = error or ResponseError(cause)
--> 519     raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
    521 log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)

MaxRetryError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /data (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x0000019F56E62C30>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)"))

During handling of the above exception, another exception occurred:

ConnectionError                           Traceback (most recent call last)
Cell In[26], line 3
      1 import requests
----> 3 response = requests.get("https://api.example.com/data")
      5 if response.status_code == 200:
      6     try:

File ~\anaconda3\Lib\site-packages\requests\api.py:73, in get(url, params, **kwargs)
     62 def get(url, params=None, **kwargs):
     63     r"""Sends a GET request.
     64
     65     :param url: URL for the new :class:`Request` object.
   (...)
     70     :rtype: requests.Response
     71     """
---> 73     return request("get", url, params=params, **kwargs)

File ~\anaconda3\Lib\site-packages\requests\api.py:59, in request(method, url, **kwargs)
     55 # By using the 'with' statement we are sure the session is closed, thus we
     56 # avoid leaving sockets open which can trigger a ResourceWarning in some
     57 # cases, and look like a memory leak in others.
     58 with sessions.Session() as session:
---> 59     return session.request(method=method, url=url, **kwargs)

File ~\anaconda3\Lib\site-packages\requests\sessions.py:589, in Session.request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, json)
    584 send_kwargs = {
    585     "timeout": timeout,
    586     "allow_redirects": allow_redirects,
    587 }
    588 send_kwargs.update(settings)
--> 589 resp = self.send(prep, **send_kwargs)
    591 return resp

File ~\anaconda3\Lib\site-packages\requests\sessions.py:703, in Session.send(self, request, **kwargs)
    700 start = preferred_clock()
    702 # Send the request
--> 703 r = adapter.send(request, **kwargs)
    705 # Total elapsed time of the request (approximately)
    706 elapsed = preferred_clock() - start

File ~\anaconda3\Lib\site-packages\requests\adapters.py:700, in HTTPAdapter.send(self, request, stream, timeout, verify, cert, proxies)
    696     if isinstance(e.reason, _SSLError):
    697         # This branch is for urllib3 v1.22 and later.
    698         raise SSLError(e, request=request)
--> 700     raise ConnectionError(e, request=request)
    702 except ClosedPoolError as e:
    703     raise ConnectionError(e, request=request)

ConnectionError: HTTPSConnectionPool(host='api.example.com', port=443): Max retries exceeded with url: /data (Caused by NameResolutionError("<urllib3.connection.HTTPSConnection object at 0x0000019F56E62C30>: Failed to resolve 'api.example.com' ([Errno 11001] getaddrinfo failed)"))
 
Python:
import requests
response = requests.get("https://www.itopya.com/gaming_k85")
response
response.status_code
response.url
response.text
response.json()

response.text yazıyorum sıkıntı yok ama response.json() yazınca hata veriyor
 
Python:
import requests
response = requests.get("https://www.itopya.com/gaming_k85")
response
response.status_code
response.url
response.text
response.json()

response.text yazıyorum sıkıntı yok ama response.json() yazınca hata veriyor
Cunku eristigin URL, JSON gondermiyor. HTML sayfayi JSON olarak parse etmeye calistigin icin hata aliyorsun.
 
Ne yapmaya calistigini anlatirsan ona gore cozum onereyim.
hocam Python'da kendimi geliştirmeye çalışıyorum response.json() yazınca her şeyi düzenli bir şekilde veriyordu ama bende hata veriyor ben kodun nasıl çalıştığını görmeye çalışıyorum
 
JSON formatinda olmayan bir seyi .json() diyerek getiremezsin. HTML ve JSON nedir onu ogrenmen lazim once. Sonrasinda da HTTP protokolunu temel mantigiyla ogrenmen lazim.

Web sitesi eger JSON formatinda yanit dondurmediyse, JSON'a donusturmek mumkun degil. Web sitesine request atarken, sadece json kabul edecegini soyleyebilirsin. Eger websitesi o formata uygun yanit verebiliyorsa verir. Ancak web sitesi bu istege yanit vermek zorunda degil. Eger gonderilen Content-Type istedigin turde degilse, ona gore sureci yonetmek requesti yapan kisi olarak senin sorumlulugun.

Ornegin;

Python:
import requests

response = requests.get("https://localhost:5050/health", headers={"Accept":"application/json"})

if "text/html" in response.headers["Content-Type"]:
    print("Got HTML: ", response.text)
elif "application/json" in response.headers["Content-Type"]:
    print("Got JSON: ", response.json())

Calistirdigimda benim sunucum health icin ne yanit veriyorsa onu gonderecek. Eger JSON gonderirse; Got JSON: <sunucudan_gelen_yanit> olacak cikti. Eger HTML gonderirse, Got HTML: <sunucudan_gelen_yanit> olacak cikti.
 

Technopat Haberler

Yeni konular

Geri
Yukarı