Got proxy authentication error in python - python

This is my code for News API, I got an error for the proxy settings, which might not be in a correct way I guess. I need help in resolving Authentication error to set proxy.
Code:
from newsapi import NewsApiClient
from requests.auth import HTTPProxyAuth
# Init
api = NewsApiClient(api_key='b6d976f8d22a4dfsdfgdfgsfASAS453410c37')
http_proxy = "https://7031:Welcome1567#58.2.64.2:31"
https_proxy = "http://7031:Welcome1567#58.2.64.2:31"
ftp_proxy = "https://7031:Welcome1567#58.2.64.2:31"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
"ftp" : ftp_proxy
}
auth = HTTPProxyAuth('username', 'mypassword')
# /v2/top-headlines
top_headlines = newsapi.get_top_headlines(q='bitcoin',
sources='bbc-news,the-verge',
category='business',
language='en',
country='us')
# /v2/everything
all_articles = newsapi.get_everything(q='bitcoin',
sources='bbc-news,the-verge',
domains='bbc.co.uk,techcrunch.com',
from_parameter='2017-12-01',
to='2017-12-12',
language='en',
sort_by='relevancy',
page=2)
# /v2/sources
sources = newsapi.get_sources()
Error I got from output is:
Output:
File "D:\anaconda3\lib\site-packages\requests\adapters.py", line 502, in send
ProxyError: HTTPSConnectionPool(host='newsapi.org', port=443): Max retries exceeded with url: /v2/top-headlines?q=bitcoin&sources=bbc-news%2Cthe-verge&language=en&country=us&category=business (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 authenticationrequired',)))

Related

Adobe Commerce Rest API Python login request

Set-up
I use the following Python code to log-in to a Adobe Commerce test environment via the Rest API,
import requests
host = 'https://b2b.test.163.com.pl'
store_code = 'PL_B2B_PL'
# Set the API endpoint for getting a customer token
endpoint = host + "/rest/" + store_code + "/V1/integration/customer/token"
# Set the credentials for the login request
credentials = {
"username": "myusername",
"password": "mypassword"
}
# Send a POST request to the login endpoint with the credentials
response = requests.post(endpoint, json=credentials, headers={"Content-Type": "application/json"})
# Check the response status code to see if the request was successful
if response.status_code == 200:
# Get the customer token from the response
customer_token = response.text
# Use the customer token in the Authorization header of subsequent API requests
headers = {
"Authorization": f"Bearer {customer_token}"
}
else:
# Handle the error response if the request was unsuccessful
print(f"Request failed: {response.text}")
Issue
Running the above code yields the following error,
ConnectionError: HTTPSConnectionPool(host='b2b.test.163.com.pl', port=443): Max retries exceeded with url: /rest/PL_B2B_PL/V1/integration/customer/token (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f7b718ed880>: Failed to establish a new connection: [Errno 60] Operation timed out'))
Question
How do I correctly connect to the test environment?
I think this code should've worked, but clearly I am wrong.

Problem while implementing my own OpenID provider and client

I am using authlib library(python) which is for client side and Oauth2 for the serverside.
after resp = oauth.get('userinfo') step my client side code stops and I get this error shown in the browser:
{ "message": "HTTPSConnectionPool(host='test.*****.com', port=8000): Max retries exceeded with url: /sample/user (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))" }
and here is my code for Oauth client side:
oauth = oauth.register(
'oauth',
client_id=env.get('client_id'),
client_secret=env.get('client_secret'),
access_token_url=env.get('access_token_url'),
access_token_params = None,
authorize_url=env.get('authorize_url'),
authorize_params=None,
api_base_url=env.get('api_base_url'),
userinfo_endpoint = env.get('userinfo_endpoint'),
client_kwargs={
'scope': 'openid',
},
)
#app.route('/login')
def login():
return oauth.authorize_redirect(redirect_uri='http://localhost:3000/callback')
#app.route('/callback')
def callback_handling():
oauth.authorize_access_token()
resp = oauth.get('userinfo')
userinfo = resp.json()
print('resp: ',vars(resp))
return redirect('http://localhost:3000/dashboard')
What could be the possible problem? where should I check? server side or client side? Do you have any clue?

Request not working for Python AWS Lambda

on a AWS Lambda function, I have a simple HTTP Request
import requests
def lambda_handler(event, context):
request_headers = {
'X-API-KEY': 'somekey',
'Content-Type':content,
'Host':'somehost',
}
resp = requests.get(some_url_here, headers=request_headers)
api_response = resp.json()
If I set the request requests.get(some_url_here, headers=request_headers, verify=False) I got no issues with the code and it works perfectly, but when I removed it it yields
Error encountered: HTTPSConnectionPool(host='x.xxx.xxx.xx', port=443): Max retries exceeded with url:some_url_here (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1124)')))
how to fix this issue?

Consuming RestApi with Requests gives SSL module is not available error

I am trying to consume a RestAPI that I have already tested in C# but now I want to rewrite the Client in Python for learing effects. I am coding in Visual Studio under Windows.
What I did yet is:
import requests
class myClass:
def __init__(self, username, password):
self.username = username
self.password = password
def getToken(self):
endpoint = "https://test.com/web/service/auth/token"
headers = {
"username" : self.username,
"password" : self.password,
"environment" : "env_me",
"grant_type" : "password",
"Content_Type" : "application/x-www-form-urlencoded"
}
r = requests.post(endpoint, headers=headers)
return print(r.json())
myObj = myClass("UN","PS")
token = myObj.getToken()
print(token)
Running this code gives me the error:
SSLError(MaxRetryError('HTTPSConnectionPool(host=\'test.com\', port=443): Max retries exceeded with url: /web/service/auth/token (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))
Since I could find any help for this I was trying to Import ssl but this gives me the error: The specific module could not be found. from ssl import ... gives me a whole bunch of stuff to choose but I do not know what to choose since I am new to Python. Could anyone help me get rid of the error?

Failed to provide proxy info to twilio pythonanywhere

I am trying to use Twilio in pythonanywhere and I know I need a proxy to make it work. My code looks like this:
class ProxiedTwilioHttpClient(HttpClient):
"""
General purpose HTTP Client for interacting with the Twilio API
"""
def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None,
allow_redirects=False):
session = Session()
session.verify = get_cert_file()
session.proxies = {
"https" : "https://52.14.161.178:3128"
}
request = Request(method.upper(), url, params=params, data=data, headers=headers, auth=auth)
prepped_request = session.prepare_request(request)
response = session.send(
prepped_request,
allow_redirects=allow_redirects,
timeout=timeout,
)
return Response(int(response.status_code), response.content.decode('utf-8'))
def send_sms(phone, content):
client = Client(api_key, api_secret, account_sid, http_client=ProxiedTwilioHttpClient())
message = client.messages.create(
to=phone,
from_="+19999999999", #of course I use the correct one
body=content)
return(message.sid)
But then it returns the following error:
.virtualenvs/sms/local/lib/python2.7/site-packages/requests/‌​adapters.py",
line 502, in send raise ProxyError(e, request=request) requests.exceptions.ProxyError:
HTTPSConnectionPool(host='api.twilio.com', port=443):
Max retries exceeded with url: /2010-04-01/Accounts/XXXXXXXXX/Messages.json (Caused by ProxyError('Cannot connect to proxy.',
NewConnectionError('<urllib3.connection.Verif iedHTTPSConnection object at 0x7fa41a55e090>:
Failed to establish a new connection: [Errno 111] Connection refused',)))
I am using the following answer that seems to work for others: https://stackoverflow.com/a/43608637/7298530
How can I solve it?
You're specifying that your code should use a proxy at https://52.14.161.178:3128. That won't work on PythonAnywhere, you need to use the proxy that the service provides. To find out what address to use for that, start a Bash console and run
echo $http_proxy
[2018 edit] We now have a specific page on getting twilio to work with the pythonanywhere proxy

Categories