Exchangelib: Can't connect to server - python

so recently I tried myself with Exchangelib, but I currently can't solve the issue. Heres my code:
from exchangelib import DELEGATE, Account, Credentials, IMPERSONATION
from exchangelib.configuration import Configuration
config = Configuration(
server='https://XXX',
credentials=Credentials(username='XXX\\XXX', password='XXX')
)
account = Account(
primary_smtp_address='mail#mail.com',
config=config,
autodiscover=False,
access_type=DELEGATE,
)
for item in account.inbox.all().order_by('-datetime_received')[:20]:
print(item.subject, item.sender, item.datetime_received)
Currently I receive the following error:
File "Project/Exchange/standardoutlook2.py", line 23, in <module>
config = Configuration(server='https://XXX', credentials=credentials)
File "Projectvenv36\lib\site-packages\exchangelib\configuration.py", line 46, in __init__
version=version
File "Projectvenv36\lib\site-packages\exchangelib\protocol.py", line 176, in __call__
protocol = super(CachingProtocol, cls).__call__(*args, **kwargs)
File "Projectvenv36\lib\site-packages\exchangelib\protocol.py", line 209, in __init__
name=self.credentials.username)
File "Projectvenv36\lib\site-packages\exchangelib\transport.py", line 149, in get_service_authtype
timeout=BaseProtocol.TIMEOUT)
File "Projectvenv36\lib\site-packages\requests\sessions.py", line 559, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "Projectvenv36\lib\site-packages\requests\sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "Projectvenv36\lib\site-packages\requests\sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "Projectvenv36\lib\site-packages\requests\adapters.py", line 412, in send
self.cert_verify(conn, request.url, verify, cert)
File "Project/Exchange/standardoutlook2.py", line 13, in cert_verify
}[urlparse(url).hostname]
KeyError: 'https'
I've added the certificate to the certificate of certifi, so when I start any request to the server outside of the code above it works well.

Related

Takes 1 positional argument but 2 error while python requests module

I have the following test code
import requests
import json
r = requests.get('https://api.github.com/user')
print(r.status_code)
This is getting the following error, I reinstalled requests and urllib3 modules but didn't help
File "/data//temp/scratchprojects/data structures/test.py", line 4, in <module>
r = requests.get('https://api.github.com/user')
File "/data/my_venv/lib/python3.8/site-packages/requests/api.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "/data/my_venv/lib/python3.8/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/data/my_venv/lib/python3.8/site-packages/requests/sessions.py", line 542, in request
resp = self.send(prep, **send_kwargs)
File "/data/my_venv/lib/python3.8/site-packages/requests/sessions.py", line 655, in send
r = adapter.send(request, **kwargs)
File "/data/my_venv/lib/python3.8/site-packages/requests/adapters.py", line 412, in send
conn = self.get_connection(request.url, proxies)
File "/data/my_venv/lib/python3.8/site-packages/requests/adapters.py", line 315, in get_connection
conn = self.poolmanager.connection_from_url(url)
File "/data/my_venv/lib/python3.8/site-packages/urllib3/poolmanager.py", line 298, in connection_from_url
return self.connection_from_host(
File "/data/my_venv/lib/python3.8/site-packages/urllib3/poolmanager.py", line 245, in connection_from_host
return self.connection_from_context(request_context)
File "/data/my_venv/lib/python3.8/site-packages/urllib3/poolmanager.py", line 260, in connection_from_context
return self.connection_from_pool_key(pool_key, request_context=request_context)
File "/data/my_venv/lib/python3.8/site-packages/urllib3/poolmanager.py", line 281, in connection_from_pool_key
pool = self._new_pool(scheme, host, port, request_context=request_context)
File "/data/my_venv/lib/python3.8/site-packages/urllib3/poolmanager.py", line 213, in _new_pool
return pool_cls(host, port, **request_context)
File "/data/my_venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 906, in __init__
HTTPConnectionPool.__init__(
File "/data/my_venv/lib/python3.8/site-packages/urllib3/connectionpool.py", line 197, in __init__
self.pool = self.QueueCls(maxsize)
TypeError: __init__() takes 1 positional argument but 2 were given
looks like a corrupted library. After removing the virtual environment and recreating it fixed the issue

“SSL: CERTIFICATE_VERIFY_FAILED” Error when publish MQTT, AWS IoT

I am getting the following error:
[ERROR] SSLError: SSL validation failed for https://data.iot.ap-northeast-2.amazonaws.com/topics/app%2Ftest%2Fresponse?qos=1 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1124)
Traceback (most recent call last):
File "/var/task/app.py", line 197, in lambda_handler
mqttcli.test('test', '11111', {}, 1, 200)
File "/opt/python/lib/python3.8/site-packages/connectors/MQTTClient.py", line 40, in test
response = self._iot_client.publish(
File "/var/task/botocore/client.py", line 357, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/var/task/botocore/client.py", line 662, in _make_api_call
http, parsed_response = self._make_request(
File "/var/task/botocore/client.py", line 682, in _make_request
return self._endpoint.make_request(operation_model, request_dict)
File "/var/task/botocore/endpoint.py", line 102, in make_request
return self._send_request(request_dict, operation_model)
File "/var/task/botocore/endpoint.py", line 136, in _send_request
while self._needs_retry(attempts, operation_model, request_dict,
File "/var/task/botocore/endpoint.py", line 253, in _needs_retry
responses = self._event_emitter.emit(
File "/var/task/botocore/hooks.py", line 356, in emit
return self._emitter.emit(aliased_event_name, **kwargs)
File "/var/task/botocore/hooks.py", line 228, in emit
return self._emit(event_name, kwargs)
File "/var/task/botocore/hooks.py", line 211, in _emit
response = handler(**kwargs)
File "/var/task/botocore/retryhandler.py", line 183, in __call__
if self._checker(attempts, response, caught_exception):
File "/var/task/botocore/retryhandler.py", line 250, in __call__
should_retry = self._should_retry(attempt_number, response,
File "/var/task/botocore/retryhandler.py", line 277, in _should_retry
return self._checker(attempt_number, response, caught_exception)
File "/var/task/botocore/retryhandler.py", line 316, in __call__
checker_response = checker(attempt_number, response,
File "/var/task/botocore/retryhandler.py", line 222, in __call__
return self._check_caught_exception(
File "/var/task/botocore/retryhandler.py", line 359, in _check_caught_exception
raise caught_exception
File "/var/task/botocore/endpoint.py", line 200, in _do_get_response
http_response = self._send(request)
File "/var/task/botocore/endpoint.py", line 269, in _send
return self.http_session.send(request)
File "/var/task/botocore/httpsession.py", line 281, in send
raise SSLError(endpoint_url=request.url, error=e)
This is the code that is causing this error:
_iot_client = boto3.client('iot-data',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name= REGION_NAME)
response = _iot_client.publish(
topic = "app/test/response",
qos = 1,
payload = json.dumps(
{
'msgid': msgid,
'status': status,
'data': payload
}
)
)
There is no error in S3 or other services through boto3. only iot-data.
It works without any problems when i run the .py.
but an error occurs when running after deploy to lambda.
There was no error until recently.
We also are experiencing this issue, in our case, an update in the "certifi" library (requests dependency) was causing some conflict with boto3 iot publish, rolling back the version solved the problem, although we are not entirely sure what exactly was failing.
You need to get the "Data-ATS" endpoint instead of the untrusted "Symantec" endpoint that's built-in. Try this:
import boto3
def get_aws_iot_ats_endpoint():
"""
Get the "Data-ATS" endpoint instead of the
untrusted "Symantec" endpoint that's built-in.
"""
iot_client = boto3.client(
"iot",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name= REGION_NAME,
verify=True
)
details = iot_client.describe_endpoint(endpointType="iot:Data-ATS")
host = details.get("endpointAddress")
return f"https://{host}"
IOT_DATA_ENDPOINT = get_aws_iot_ats_endpoint()
client_iot = boto3.client(
"iot-data",
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name= REGION_NAME,
verify=True,
endpoint_url=IOT_DATA_ENDPOINT
)
response = client_iot.publish(
topic = "app/test/response",
qos = 1,
payload = json.dumps(
{
'msgid': msgid,
'status': status,
'data': payload
}
)
)
I had the same error.
Simply insert this at the beginning of your code:`
from botocore.exceptions import ClientError
It should work.
Best.

Python & Nameko - GreenSSLSocket does not have a public constructor. Instances are returned by SSLContext.wrap_socket().

I've created a nameko service that sends a text message to the provided phone number. Using the Africas Talking API. The service runs successfully but once you use the nameko shell it doesn't work. However the phone number is successfully passed into the service.
Nameko Shell:
>>> n.rpc.sms.text('+254712619789')
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/nameko/rpc.py", line 369, in __call__
return reply.result()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/nameko/rpc.py", line 327, in result
raise deserialize(error)
nameko.exceptions.RemoteError: TypeError GreenSSLSocket does not have a public constructor. Instances are returned by SSLContext.wrap_socket().
Nameko Service
nameko run at
starting services: sms
Connected to amqp://guest:**#127.0.0.1:5672//
+254712619789
error handling worker <WorkerContext [sms.text] at 0x10414a128>: GreenSSLSocket does not have a public constructor. Instances are returned by SSLContext.wrap_socket().
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/nameko/containers.py", line 391, in _run_worker
result = method(*worker_ctx.args, **worker_ctx.kwargs)
File "./at.py", line 23, in text
response = sms.send("Hello Message!", [phone_no])
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/africastalking/SMS.py", line 32, in send
return self._make_request(url, 'POST', headers=self._headers, params=None, data=data, callback=callback)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/africastalking/Service.py", line 92, in _make_request
res = self.__make_post_request(url=url, headers=headers, data=data, params=params)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/africastalking/Service.py", line 78, in __make_post_request
data=data,
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/api.py", line 112, in post
return request('post', url, data=data, json=json, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 512, in request
resp = self.send(prep, **send_kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/sessions.py", line 622, in send
r = adapter.send(request, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/adapters.py", line 445, in send
timeout=timeout
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connectionpool.py", line 343, in _make_request
self._validate_conn(conn)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connectionpool.py", line 849, in _validate_conn
conn.connect()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/connection.py", line 356, in connect
ssl_context=context)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/urllib3/util/ssl_.py", line 359, in ssl_wrap_socket
return context.wrap_socket(sock, server_hostname=server_hostname)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/eventlet/green/ssl.py", line 402, in wrap_socket
return GreenSSLSocket(sock, *a, _context=self, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/eventlet/green/ssl.py", line 68, in __init__
ca_certs, do_handshake_on_connect and six.PY2, *args, **kw)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 788, in __init__
f"{self.__class__.__name__} does not have a public "
TypeError: GreenSSLSocket does not have a public constructor. Instances are returned by SSLContext.wrap_socket().
at.py
import json
from nameko.web.handlers import http
from nameko.rpc import rpc
import africastalking
class HttpService(object):
name = "sms"
#rpc
def text(self, phone_no):
print (phone_no)
africastalking.initialize(username, api_key)
# Initialize a service e.g. SMS
sms = africastalking.SMS
# Use the service synchronously
response = sms.send("Hello Message!", [phone_no])
print(response)
return response
the issue might be eventlet not being compatible with python 3.7. Could you try with python 3.6?
(see e.g. https://github.com/eventlet/eventlet/issues/502)

uploading an image file to aws s3 using python

import tinys3
conn =tinys3.Connection(aws_key_id,aws_secrert_key)
f = open('c:/Users/Akhil/Downloads/New/img033.jpg','rb')
conn.upload('c:/Users/Akhil/Downloads/New/img033.jpg',f,'matt3r')
I am trying to upload an image present in local directory shown below to aws s3 matt3r bucket. when I run this I am getting the following error :
Traceback (most recent call last):
File "conn.py", line 6, in <module>
conn.upload('c:/Users/Akhil/Downloads/New/img033.jpg',f,'matt3r')
File "C:\Python27\lib\site-packages\tinys3\connection.py", line 171, in upload
return self.run(r)
File "C:\Python27\lib\site-packages\tinys3\connection.py", line 262, in run
return self._handle_request(request)
File "C:\Python27\lib\site-packages\tinys3\connection.py", line 356, in _handle_request
return request.run()
File "C:\Python27\lib\site-packages\tinys3\request_factory.py", line 346, in run
auth=self.auth)
File "C:\Python27\lib\site-packages\requests\api.py", line 123, in put
return request('put', url, data=data, **kwargs)
File "C:\Python27\lib\site-packages\requests\api.py", line 56, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "C:\Python27\lib\site-packages\requests\sessions.py", line 596, in send
r = adapter.send(request, **kwargs)
File "C:\Python27\lib\site-packages\requests\adapters.py", line 473, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(10054, 'An existing connection was forcibly closed by the remote host'))
You need to add policy for AWS S3 to your IAM user.

python oauthlib: in escape ValueError "Only unicode objects are escapable"

I'm using python-social-auth to login with social networks from my Django application. On my local machine everything works fine, but when I deploy to a server I get the following error:
oauthlib.oauth1.rfc5849.utils in escape
ValueError: Only unicode objects are escapable. Got None of type <type 'NoneType'>.
Stacktrace:
File "django/core/handlers/base.py", line 112, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "social/apps/django_app/utils.py", line 45, in wrapper
return func(request, backend, *args, **kwargs)
File "social/apps/django_app/views.py", line 12, in auth
return do_auth(request.social_strategy, redirect_name=REDIRECT_FIELD_NAME)
File "social/actions.py", line 25, in do_auth
return strategy.start()
File "social/strategies/base.py", line 66, in start
return self.redirect(self.backend.auth_url())
File "social/backends/oauth.py", line 99, in auth_url
token = self.set_unauthorized_token()
File "social/backends/oauth.py", line 158, in set_unauthorized_token
token = self.unauthorized_token()
File "social/backends/oauth.py", line 177, in unauthorized_token
method=self.REQUEST_TOKEN_METHOD)
File "social/backends/base.py", line 202, in request
response = request(method, url, *args, **kwargs)
File "requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "requests/sessions.py", line 349, in request
prep = self.prepare_request(req)
File "requests/sessions.py", line 287, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
File "requests/models.py", line 291, in prepare
self.prepare_auth(auth, url)
File "requests/models.py", line 470, in prepare_auth
r = auth(self)
File "requests_oauthlib/oauth1_auth.py", line 87, in __call__
unicode(r.url), unicode(r.method), None, r.headers)
File "oauthlib/oauth1/rfc5849/__init__.py", line 293, in sign
request.oauth_params.append(('oauth_signature', self.get_oauth_signature(request)))
File "oauthlib/oauth1/rfc5849/__init__.py", line 128, in get_oauth_signature
uri, headers, body = self._render(request)
File "oauthlib/oauth1/rfc5849/__init__.py", line 199, in _render
headers = parameters.prepare_headers(request.oauth_params, request.headers, realm=realm)
File "oauthlib/oauth1/rfc5849/utils.py", line 31, in wrapper
return target(params, *args, **kwargs)
File "oauthlib/oauth1/rfc5849/parameters.py", line 57, in prepare_headers
escaped_value = utils.escape(value)
File "oauthlib/oauth1/rfc5849/utilsy", line 56, in escape
'Got %s of type %s.' % (u, type(u)))
Some packages from requirements.txt file:
Django==1.6.6
google-api-python-client==1.1
oauth2==1.5.211
oauthlib==0.6.3
python-openid==2.2.5
python-social-auth==0.1.26
requests==2.4.0
requests-oauthlib==0.4.1
six==1.7.3
I got this error when I did not provide my OAuth Consumer key and secrets in my django settings file. It's essentially a "Required setting not found" error. Is it worth checking all your settings copied across successfully when you deployed?
I've upgraded to python-social-auth and had the same problem with Linkedin login. Parameter names in settings are changed in the latest version so instead:
LINKEDIN_CONSUMER_KEY and LINKEDIN_CONSUMER_SECRET it'd be used: SOCIAL_AUTH_LINKEDIN_KEY and SOCIAL_AUTH_LINKEDIN_SECRET.
the problem comes to you if this statement have spelling mistake:
tweepy.OAuthHandler(consumer_key,consumer_secret)

Categories