Invalid Post: 400 — Bad Request with Python requests
Solution 1: I was able to create a list with your sample by fixing the capitalization of False to false and isAnonymous to IsAnonymous in the payload. It exposes a session attribute you can use for authenticated requests.
Python requests — remove headers on redirect
curl does not drop the Host header. It sends a second request with the header Host: www.google.co.uk (created from URL to which the redirect leads).
As ZhongYu wrote, you don’t need to specify the Host header. So if your goal was only to download the page, the solution would be simply to omit the headers argument:
response = s.get("http://google.co.uk",allow_redirects=True)
But if your goal is some http checking on, may be this would be the solution:
import requests resp = requests.get("http://google.co.uk",allow_redirects=False) while resp.status_code == 301: resp = requests.get(resp.headers['location'],allow_redirects=False)
Very late reply. I just came across this post looking for something else. It may help somebody looking for an answer.
Look into the request «hook» mechanism, you can specify a callback when the response comes back (each response will call your hook): https://2.python-requests.org/en/master/user/advanced/#event-hooks
From within the callback, you will be able to remove/modify/add the header(either blindly or when the status code is 3xx or . ).
Invalid Post: 400 — Bad Request with Python requests, Invalid Post: 400 — Bad Request with Python requests. Ask Question Asked 4 years, 10 months ago. Modified 4 years, 10 months ago. Viewed 9k times 3 I’m using PoliteMail’s ODATA RESTful API (Doc: PoliteMail API Entity Directory) I’m trying to create a Contact inside of PoliteMail with requests.post(). Below are my …
Invalid Post: 400 — Bad Request with Python requests
I was able to create a list with your sample by fixing the capitalization of False to false and isAnonymous to IsAnonymous in the payload.
You also mentioned creating a Contact at the beginning of your post. I was able to successfully create a Contact with the following.
I work at PoliteMail and have made an internal request to get the documentation updated to fix the capitalization of IsAnonymous .
UPDATE: The documentation has been updated with the correct capitalization. http://kb.politemail.com/?p=1349
From the error log, server side may not handle the line break \r\n .
Can you try to remove the line break of your payload?
Python 3.x — How to work with request.post() method, Another approach is using threads, they can call the url seperately wait for the response without affecting rest of your code. Something like this will help: def request_task (url, json, headers): requests.post (url, json=data, headers=headers) def fire_and_forget (url, json, headers): threading.Thread …
Python Requests — retry request after re-authentication
Here’s the same solution but without using a class
session = requests.Session() session.headers.update() def refresh_token(r, *args, **kwargs): if r.status_code == 401: logger.info("Fetching new token as the previous token expired") token = get_token() session.headers.update(">) r.request.headers["Authorization"] = session.headers["Authorization"] return session.send(r.request, verify=False) session.hooks['response'].append(refresh_token)
The eventual code I came up with to solve this. It is more complete than OP. It exposes a session attribute you can use for authenticated requests.
The reason why you have to recall auth is because .send just sends the PreparedRequest.
If you don’t like the REATTEMPT header I added to prevent infinite recursion. You can also de-register the hook like OP mentioned (but you have to register it again for use in the future), or in my coded class instead do the new request with self._session instead of self.session . ( self._session is just a session without hooks.)
import requests from urllib.parse import urljoin class JWTAuth: def __init__(self, user, passw, base): self.base = base self.user, self.passw = user, passw self._session = requests.Session() # Session for tokens self.authenticate() self.session = requests.Session() # Authenticated session self.session.auth = self.auth self.session.hooks['response'].append(self.reauth) def abs_url(self, path): """Combine the base url with a path.""" return urljoin(self.base, path) def auth(self, req): """Just set the authentication token, on every request.""" req.headers['Authorization'] = f'JWT ' return req def reauth(self, res, *args, **kwargs): """Hook to re-authenticate whenever authentication expires.""" if res.status_code == requests.codes.unauthorized: if res.request.headers.get('REATTEMPT'): res.raise_for_status() self.refresh_auth() req = res.request req.headers['REATTEMPT'] = 1 req = self.session.auth(req) res = self.session.send(req) return res def refresh_auth(self): """Use the refresh token to get a new access token.""" res = self._session.post(self.abs_url("api/token/refresh/"), data=) if res.status_code == 200: self.access = res.json()['access'] else: # Token expired -> re-authenticate self.authenticate() def authenticate(self): res = self._session.post( self.abs_url("api/token/"), data=, ) res.raise_for_status() data = res.json() self.refresh, self.access = data['refresh'], data['access']
So I got in touch with the Requests author discussing an unrelated issue and asked about this, and it turns out this approach is Ok. The only changed I did was to drop the custom header (it does work and is also Ok) and now I just deregister the response hook within the hook before re-sending the request. This breaks the loop and all is nice.
Get — Python requests library how to pass, As you wanting requests to use Basic Authentication and craft an authorization header like so: ‘VE9LOjxNWV9UT0tFTj4K’. Which is the base64 representation of ‘TOK:
Python Requests authentication with proxy for POST call
The problem you are having seems to be caused by an untrusted SSL certificate.
The quickest fix is setting verify=False . Please note that this will cause the certificate not to be verified and expose your application to security risks. But as you mensioned, it is running in a safe network so this is not a serious problem.
s = requests.session() s.auth = pageCert = requests.post(post_url_finance, proxies=proxies, verify=False)
I used s.auth with verify=False. This gave me a response back instead of giving me the SSL error.
Recreate POST request with WebKitFormBoundary, When you’re sending an ajax request via jQuery and you want to send FormData you don’t need to use JSON.stringify on this FormData. Also when you’re sending file the content type must be multipart/form-data including boundry — something like this multipart/form-data; boundary=— …