How to fix error in python requests?
I am using an API, which receives a pdf file and does some analysis, but I am receiving Response 500 always Have initially tested using Postman and the request goes through, receiving response 200 with the corresponding JSON information. The SSL security should be turned off. However, when I try to do request via Python, I always get Response 500 Python code written by me:
import requests url = "https://>/api/v1/documents" fin = open('/home/train/aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf', 'rb') files = r = requests.post(url, files=files, verify=False) print (r) #r.text is empty
import requests url = "https://>/api/v1/documents" payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf\"\r\nContent-Type: application/pdf\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--" headers = < 'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW", 'Content-Type': "application/x-www-form-urlencoded", 'cache-control': "no-cache", 'Postman-Token': "65f888e2-c1e6-4108-ad76-f698aaf2b542" >response = requests.request("POST", url, data=payload, headers=headers) print(response.text)
< "id": "5e69058e2690d5b0e519cf4006dfdbfeeb5261b935094a2173b2e79a58e80ab5", "name": "aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf", "fileIds": < "original": "5e69058e2690d5b0e519cf4006dfdbfeeb5261b935094a2173b2e79a58e80ab5.pdf" >, "creationDate": "2019-06-20T09:41:59.5930472+00:00" >
UPDATE: Tried the GET request — works fine, as I receive the JSON response from it. I guess the problem is in posting pdf file. Is there any other options on how to post a file to an API? Postman Response RAW:
POST /api/v1/documents Content-Type: multipart/form-data; boundary=--------------------------375732980407830821611925 cache-control: no-cache Postman-Token: 3e63d5a1-12cf-4f6b-8f16-3d41534549b9 User-Agent: PostmanRuntime/7.6.0 Accept: */* Host: > cookie: c2b8faabe4d7f930c0f28c73aa7cafa9=736a1712f7a3dab03dd48a80403dd4ea accept-encoding: gzip, deflate content-length: 3123756 file=[object Object] HTTP/1.1 200 status: 200 Date: Thu, 20 Jun 2019 10:59:55 GMT Content-Type: application/json; charset=utf-8 Transfer-Encoding: chunked Location: /api/v1/files/95463e88527ecdc94393fde685ab1d05fa0ee0b924942f445b14b75e983c927e api-supported-versions: 1.0 X-Frame-Options: SAMEORIGIN X-XSS-Protection: 1; mode=block X-Content-Type-Options: nosniff Strict-Transport-Security: max-age=31536000; includeSubDomains; preload Referrer-Policy: strict-origin ,"creationDate":"2019-06-20T10:59:55.7038573+00:00">
import requests files = < 'file': open('/home/train/aab2wieuqcnvn3g6syadumik4bsg5.0062.pdf', 'rb'), >response = requests.post('>/api/v1/documents', files=files, verify=False) print (response.text)
Requests ошибка 500 в post запросе
Необходимо отправить словарь в пост запросе на страницу сайта.
Открываю http://localhost:5000/post — выдает ошибку post 500
Не могу понять почему? Он же должен просто открыть страницу node? или я должен передать в node эти две перменные? Сорри, я нуб
1 2 3 4 5 6 7 8 9 10 11 12 13 14
@app.route('/post', methods=['GET', 'POST']) def post_to_node(): base_url = "http://localhost:5000/node" payload = {'key1': 'value1', 'key2': 'value2'} response = requests.post(base_url, data=payload, timeout=0.001) return print(response.text) # TEXT/HTML @app.route('/node', methods=['GET', 'POST']) def node(): response = { 'send adress': request.form['key1'], 'send atom': request.form['key2'], } return jsonify(response), 200
Постоянная ошибка 415 при попытке сделать post запрос через библиотеку requests
Пытаюсь сделать post запрос с помощью модуля requests на данную страницу.
Ошибка 500 при пост запросе
При отправке формы возникает ошибка(на изображении) и она видна только в консоли, POST парметры.
Ошибка 500 при запросе к WebAPI
Привет. Помогите пожалуйста разобраться. Есть action на API контроллере controller .
ошибка 500 при jax запросе на контроллер
Здравствуйте. Подскажите пожалуйста в чем может быть причина ошибки. При имитации запроса на метод.
Вместо return print(response.text) # TEXT/HTML :
return jsonify(response.json()), 200
Сообщение от lapitsky
Рыжий Лис, Пальцем в небо, но всё же, Flask позволяет возвращать None ?
1. None поправил
2. timeout=0.001 — без этого параметра ошибка такая же
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
@app.route('/node', methods=['GET', 'POST']) def node(): response = { 'send adress': request.form['key1'], 'send atom': request.form['key2'], } return jsonify(response), 200 @app.route('/post', methods=['GET', 'POST']) def post_to_node(): base_url = "http://localhost:5000/node" payload = {'key1': 'value1', 'key2': 'value2'} response = requests.post(base_url, data=payload, timeout=0.001) #response = requests.get(base_url, data=payload, timeout=0.001) res = response.text if print(response.text) is not None: res = response.text else: res = 'none' return print(res)# TEXT/HTML
Добавлено через 3 минуты
Лог ошибки:
C:\Users\230\AppData\Local\Programs\Python\Python36-32\python.exe C:/Work/phyton/main.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
[2018-04-02 21:02:32,454] ERROR in app: Exception on /post [GET]
Traceback (most recent call last):
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py», line 387, in _make_request
six.raise_from(e, None)
File «», line 2, in raise_from
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py», line 383, in _make_request
httplib_response = conn.getresponse()
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\http\client.py», line 1331, in getresponse
response.begin()
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\http\client.py», line 297, in begin
version, status, reason = self._read_status()
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\http\client.py», line 258, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), «iso-8859-1»)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\socket.py», line 586, in readinto
return self._sock.recv_into(b)
socket.timeout: timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\adapters.py», line 440, in send
timeout=timeout
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py», line 639, in urlopen
_stacktrace=sys.exc_info()[2])
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\util\retry.py», line 357, in increment
raise six.reraise(type(error), error, _stacktrace)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\packages\six.py», line 686, in reraise
raise value
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py», line 601, in urlopen
chunked=chunked)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py», line 389, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\urllib3\connectionpool.py», line 309, in _raise_timeout
raise ReadTimeoutError(self, url, «Read timed out. (read timeout=%s)» % timeout_value)
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host=’localhost’, port=5000): Read timed out. (read timeout=1)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py», line 1982, in wsgi_app
response = self.full_dispatch_request()
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py», line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py», line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py», line 33, in reraise
raise value
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py», line 1612, in full_dispatch_request
rv = self.dispatch_request()
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py», line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File «C:/Work/phyton/main.py», line 148, in post_to_node
response = requests.post(base_url, data=payload, timeout=1)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\api.py», line 112, in post
return request(‘post’, url, data=data, json=json, **kwargs)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\api.py», line 58, in request
return session.request(method=method, url=url, **kwargs)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\sessions.py», line 508, in request
resp = self.send(prep, **send_kwargs)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\sessions.py», line 618, in send
r = adapter.send(request, **kwargs)
File «C:\Users\230\AppData\Local\Programs\Python\Python36-32\lib\site-packages\requests\adapters.py», line 521, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPConnectionPool(host=’localhost’, port=5000): Read timed out. (read timeout=1)
127.0.0.1 — — [02/Apr/2018 21:02:32] «GET /post HTTP/1.1» 500 —
127.0.0.1 — — [02/Apr/2018 21:02:32] «POST /node HTTP/1.1» 200 —
Добавлено через 2 минуты
если таймаут убрать, страница бесконечно пытается грузится с пустым экраном
python requests login post get response code 500
when i run the code ,i get the response 500,but when i copy this link with params in the browser,it works and i could login. i cannot find the reason .i need the help,thanks!
There are many reasons why this could fail. For example, the login page may require some cookies to be set before making the login attempt. Or there might be some other request header that you are missing.
Response code 500 means a server side error. Do you get back any information on the error page send from the server? Do you have access to the server and can check with the log files of that server?
2 Answers 2
header_content = js_data = json.dumps() response = requests.post(link, data=js_data, headers=header_content, verify=False) if response.status_code == 200: print(response.content)
You need to specify content in the header, in your case it is json. Also, as you perform a request through https, certificate verification could cause a problem, so turn the verification off by «verify=False». Also error in json format could be a reason of 500, so to be sure that you are passing appropriate json object, I recommend to use json.dumps(). Hope it helps. Regards!
when you get this error, first check to see if your webpage can be loaded in a browser or not .
it may shows some errors about permission. In this case, change the permission of your codeigniter folder with this command:
$ sudo chmod 755 -R /var/www/html/Codeigniter_folder_name
Status code 500 not treated as exception
Making a request to the server, as in code below, I’ve got status code 500, which was not caught as an exception. The output was «500», but I need for all 500 codes to result in sys.exit(). Does requests.exceptions.RequestException not treat 500 as an exception or is it something else? The requests module docs http://docs.python-requests.org/en/latest/user/quickstart/#errors-and-exceptions are not very clear on what falls under this class. How do I make sure that all 500 codes result in sys.exit()?
import requests import json import sys url = http://www.XXXXXXXX.com headers = try: r = requests.post(url, headers=headers) status = r.status_code response = json.dumps(r.json(), sort_keys=True, separators=(',', ': ')) print status except requests.exceptions.RequestException as e: print "- ERROR - Web service exception, msg = <>".format(e) if r.status_code < 500: print r.status_code else: sys.exit(-1)
3 Answers 3
A status code 500 is not an exception. There was a server error when processing the request and the server returned a 500; more of a problem with the server than the request.
You can therefore do away with the try-except :
r = requests.post(url, headers=headers) status = r.status_code response = json.dumps(r.json(), sort_keys=True, separators=(',', ': ')) if str(status).startswith('5'): .
Except in this case if it's a 501 or any other code, you'd have to code in every number above 500. Only useful if you know what response code the server will return, guaranteed