Cannot run bind() with ldap3 in python3 - python-3.x

Below is my code to try and query my ldap server. However, for some reason, I cannot seem to make the bind command work to progress in my code. I continue to get the following message and am not sure what it means or how to fix it. I apologize about the error message formatting. I tried my best to make it as readable as possible.
Any help would be greatly appreciated!
>>> from ldap3 import Server, Connection, SUBTREE
>>> server = Server('<server_name>')
>>> conn = Connection(server, user='<username>', password='<password>')
>>> conn.open()
>>> conn.bind()
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.5/site-packages/ldap3/core/connection.py", line 427, in bind
response = self.post_send_single_response(self.send('bindRequest', request, controls))
File "/usr/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 122, in post_send_single_response
responses, result = self.get_response(message_id)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/base.py", line 298, in get_response
responses = self._get_response(message_id)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 168, in _get_response
dict_response = self.decode_response(ldap_resp)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/base.py", line 403, in decode_response
result = bind_response_to_dict(component)
File "/usr/lib/python3.5/site-packages/ldap3/operation/bind.py", line 119, in bind_response_to_dict
'saslCreds': bytes(response['serverSaslCreds']) if response['serverSaslCreds'] is not None else None}
File "/usr/lib/python3.5/site-packages/pyasn1/type/univ.py", line 984, in bytes
return bytes(self._value)
File "/usr/lib/python3.5/site-packages/pyasn1/type/base.py", line 164, in plug
raise error.PyAsn1Error('Uninitialized ASN.1 value ("%s" attribute looked up)' % name)
pyasn1.error.PyAsn1Error: Uninitialized ASN.1 value ("len" attribute looked up)

Related

What should I infer from the error: AttributeError: 'str' object has no attribute 'setdefault'

I have a python repository, which tries to connect with a database available on web and collect the relevant data. Now when I run the repo from local machine, I get the desired database and hence the output.
However, when I run the same code from the Windows Server and tries to connect the same website(proxy), I am getting the above error.
I have installed/uninstalled the respective ODBC driver but no luck
Can anyone suggest me any method to get out of this?
(ssf) C:\Users\admin-prakuma3\data-model_1>python main.py
Traceback (most recent call last):
File "main.py", line 612, in <module>
salesforce_daily_extractors()
File "main.py", line 44, in salesforce_daily_extractors
'StartDate': 'StartDate'
File "C:\Users\admin-prakuma3\data-model_1\SalesforceExtractor.py", line 23, in __run__
fields = sg.getConnection(sg).__getattr__(sfdc_object).describe()['fields']
File "C:\Users\admin-prakuma3\data-model_1\SalesforceGateway.py", line 19, in getConnection
security_token='************', proxies="*******:8080")
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\simple_salesforce\api.py", line 146, in __init__
domain=self.domain)
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\simple_salesforce\login.py", line 168, in SalesforceLogin
proxies=proxies)
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\requests\sessions.py", line 535, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\requests\sessions.py", line 479, in request
prep.url, proxies, stream, verify, cert
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\requests\sessions.py", line 656, in merge_environment_settings
proxies.setdefault(k, v)
AttributeError: 'str' object has no attribute 'setdefault'

Dialogflow v2 Beta 1 Update Intent with Python

I am lost.
I have a currently existing Intent in my project, and I am trying to update ALL fields programmatically because that is what my project requires.
I read this documentation and checked this source file on GitHub, and I think the reason I am getting an error is because I don't understand this part of the source:
Args:
intent (Union[dict, ~google.cloud.dialogflow_v2beta1.types.Intent]): Required. The intent
to update.
Format: projects/<Project ID>/agent/intents/<Intent ID>.
If a dict is provided, it must be of the same form as the protobuf
message :class:~google.cloud.dialogflow_v2beta1.types.Intent
(Line 484 for reference)
The platform works great I just don't know what I am missing here..
My code
from constants import *
from google.oauth2 import service_account
import dialogflow_v2beta1
cred = service_account.Credentials.from_service_account_file(AUTH_JSON)
client = dialogflow_v2beta1.IntentsClient(credentials=cred)
params = dialogflow_v2beta1.types.Intent.Parameter(name='test', display_name='test', value='test', is_list=True)
t = dialogflow_v2beta1.types.Intent.Message.Text(text='TEST TEXT')
m = dialogflow_v2beta1.types.Intent.Message(text=t)
p = dialogflow_v2beta1.types.Intent.TrainingPhrase.Part(text='test',entity_type='#test_type', alias='test_alias', user_defined=True)
t = dialogflow_v2beta1.types.Intent.TrainingPhrase(name='test',type=2, parts=[p])
modified_intent = dialogflow_v2beta1.types.Intent(
display_name='test',
messages=[m],
webhook_state=1,
is_fallback=False,
ml_disabled=False,
input_context_names=PROJECT_DIR+'agent/sessions/-/contexts/' + 'TEST_CONTEXT',
events='TESTING EVENT',
training_phrases=[t],
action='TESTING ACTION',
reset_contexts=False,
parameters=[params]
)
name = client.intent_path(PROJECT_NAME, '7b8f2105-53d4-4724-8d4c-0170b8db7028')
intent = client.get_intent(name)
client.update_intent(intent=modified_intent, language_code=LANGUAGE_CODE, intent_view=0)
Full error message
Traceback (most recent call last):
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/anaconda/envs/data/lib/python3.6/site-packages/grpc/_channel.py", line 550, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/anaconda/envs/data/lib/python3.6/site-packages/grpc/_channel.py", line 467, in _end_unary_response_blocking
raise _Rendezvous(state, None, None, deadline)
grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with:
status = StatusCode.INVALID_ARGUMENT
details = "Resource name '' does not match 'projects/*/agent/intents/*'."
debug_error_string = "{"created":"#1552461629.958860000","description":"Error received from peer","file":"src/core/lib/surface/call.cc","file_line":1036,"grpc_message":"Resource name '' does not match 'projects/*/agent/intents/*'.","grpc_status":3}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "test.py", line 26, in <module>
client.update_intent(intent=modified_intent, language_code=LANGUAGE_CODE, intent_view=0)
File "/anaconda/envs/data/lib/python3.6/site-packages/dialogflow_v2beta1/gapic/intents_client.py", line 535, in update_intent
request, retry=retry, timeout=timeout, metadata=metadata)
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/retry.py", line 270, in retry_wrapped_func
on_error=on_error,
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/retry.py", line 179, in retry_target
return target()
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/anaconda/envs/data/lib/python3.6/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.InvalidArgument: 400 Resource name '' does not match 'projects/*/agent/intents/*'.
You are able to get the intent which you want to modify correctly by using
name = client.intent_path(PROJECT_NAME, your_intent_id)
You will get complete definition of your intent.
Then you need to change the values of this intent by accessing them and assigning your values.
After that, you need to pass the same intent in your update_intent() function.
It is also advised to use update_mask to avoid changing any other field or setting rest of the fields None.
Here is an example of updating intent display_name from greet to hello:
client = dialogflow.IntentsClient()
intent_name = client.intent_path(project_id, intent_id)
intent = client.get_intent(intent_name, intent_view=dialogflow.enums.IntentView.INTENT_VIEW_FULL)
intent.display_name = 'hello'
update_mask = field_mask_pb2.FieldMask(paths=['display_name'])
print(response)
You will need ope extra import as well in your code:
from google.protobuf import field_mask_pb2
This way, intent's display_name will be changed.
You can do same for the rest of your properties as well. Just remember to pass the value which the property is expecting by following this documentation and you can take help from this issue as well.
Hope it helps.

ReadTimeOut Error while writer.write(xlist) in Alibaba odps connection. Any Suggestion?

from odps import ODPS
from odps import options
import csv
import os
from datetime import timedelta, datetime
options.sql.use_odps2_extension = True
options.tunnel.use_instance_tunnel = True
options.connect_timeout = 60
options.read_timeout=130
options.retry_times = 7
options.chunk_size = 8192*2
odps = ODPS('id','secret','project', endpoint ='endpointUrl')
table = odps.get_table('eventTable')
def uploadFile(file):
with table.open_writer(partition=None) as writer:
with open(file, 'rt') as csvfile:
rows = csv.reader(csvfile, delimiter='~')
for final in rows:
writer.write(final)
writer.close();
uploadFile('xyz.csv')
Assume I pass number of files in uploadFile call one by one from directory To connect alibaba cloud from python to migrate data into max compute table over the cloud. When I run this code, service stops either after working long time or at night time. It reports me error Read Time Out Error at line writer.write(final).
Error:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/urllib3/response.py", line 226, in _error_catcher
yield
File "/usr/lib/python3/dist-packages/urllib3/response.py", line 301, in read
data = self._fp.read(amt)
File "/usr/lib/python3.5/http/client.py", line 448, in read
n = self.readinto(b)
File "/usr/lib/python3.5/http/client.py", line 488, in readinto
n = self.fp.readinto(b)
File "/usr/lib/python3.5/socket.py", line 575, 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 "/usr/lib/python3/dist-packages/requests/models.py", line 660, in generate
for chunk in self.raw.stream(chunk_size, decode_content=True):
File "/usr/lib/python3/dist-packages/urllib3/response.py", line 344, in stream
data = self.read(amt=amt, decode_content=decode_content)
File "/usr/lib/python3/dist-packages/urllib3/response.py", line 311, in read
flush_decoder = True
File "/usr/lib/python3.5/contextlib.py", line 77, in __exit__
self.gen.throw(type, value, traceback)
File "/usr/lib/python3/dist-packages/urllib3/response.py", line 231, in _error_catcher
raise ReadTimeoutError(self._pool, None, 'Read timed out.')
requests.packages.urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='dt.odps.aliyun.com', port=80): Read timed out.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/dataUploader.py", line 66, in <module>
uploadFile('xyz.csv')
File "/dataUploader.py", line 53, in uploadFile
writer.write(final)
File "/usr/local/lib/python3.5/dist-packages/odps/models/table.py", line 643, in __exit__
self.close()
File "/usr/local/lib/python3.5/dist-packages/odps/models/table.py", line 631, in close
upload_session.commit(written_blocks)
File "/usr/local/lib/python3.5/dist-packages/odps/tunnel/tabletunnel.py", line 308, in commit
in self.get_block_list()])
File "/usr/local/lib/python3.5/dist-packages/odps/tunnel/tabletunnel.py", line 298, in get_block_list
self.reload()
File "/usr/local/lib/python3.5/dist-packages/odps/tunnel/tabletunnel.py", line 238, in reload
resp = self._client.get(url, params=params, headers=headers)
File "/usr/local/lib/python3.5/dist-packages/odps/rest.py", line 138, in get
return self.request(url, 'get', stream=stream, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/odps/rest.py", line 125, in request
proxies=self._proxy)
File "/usr/lib/python3/dist-packages/requests/sessions.py", line 608, in send
r.content
File "/usr/lib/python3/dist-packages/requests/models.py", line 737, in content
self._content = bytes().join(self.iter_content(CONTENT_CHUNK_SIZE)) or bytes()
File "/usr/lib/python3/dist-packages/requests/models.py", line 667, in generate
raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='dt.odps.aliyun.com', port=80): Read timed out.
packet_write_wait: Connection to 122.121.122.121 port 22: Broken pipe
This is the error what I got. Can you suggest what is the problem ?
The read timeout is the timeout on waiting to read data. Usually, if the server fails to send a byte seconds after the last byte, a read timeout error will be raised.
This happens because of the server couldn`t read the file within the specified timeout period.
Here, the read timeout was set to 130 seconds, which is less if your file size is very high.
Please increase the timeout limit from 130 seconds to 500 seconds, i.e options.read_timeout=130 to options.read_timeout=500
It would resolve your problem, at the same time minimize the retry times from 7 to 3,
i.e options.retry_times=7 to options.retry_times=3
This error is usually caused by network issue.
Execute curl endpoint URL in a terminal. If it returns immediately with something like this:
<?xml version="1.0" encoding="UTF-8"?>
<Error>
<Code>NoSuchObject</Code>
<Message><![CDATA[Unknown http request location: /]]></Message>
<RequestId>5E5CC9526283FEC94F19DAAE</RequestId>
<HostId>localhost</HostId>
</Error>
Then the endpoint URL is reachable. But if it hangs, then you should check if you are using the right endpoint URL.
Since MaxCompute (ODPS) has public and private endpoint, it could be confusing sometimes.

exchangelib get task from task queryset MIME conversion is not supported for this item

I am trying to access an object
through a queryset created with exchangelib however I get an error MIME CONVERSION IS NOT SUPPORTED FOR THIS ITEM, I don't know what it means. I have tried the same code with calendar items and I have no problem whatsoever. thanks
from exchangelib import Account, Credentials, DELEGATE
credentials = Credentials(username='BUREAU\\pepe', password='pepe')
pepe_account = Account(
primary_smtp_address='pepe#office.com',
credentials=credentials,
autodiscover=True,
access_type=DELEGATE)
tasks = pepe_account.tasks.filter()
print(tasks) -- Works
for task in tasks:
print(task)
The iteration fails, instead of print(task) I also tried pass and I get the same message.
Traceback (most recent call last):
File "test.py", line 13, in <module>
for task in tasks:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/queryset.py", line 197, in __iter__
for val in result_formatter(self._query()):
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/queryset.py", line 272, in _as_items
for i in iterable:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/account.py", line 393, in fetch
for i in GetItem(account=self).call(items=ids, additional_fields=additional_fields, shape=IdOnly):
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 456, in _pool_requests
for elem in elems:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 283, in _get_elements_in_response
container_or_exc = self._get_element_container(message=msg, name=self.element_container_name)
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 256, in _get_element_container
self._raise_errors(code=response_code, text=msg_text, msg_xml=msg_xml)
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 273, in _raise_errors
raise vars(errors)[code](text)
exchangelib.errors.ErrorUnsupportedMimeConversion: MIME conversion is not supported for this item type.

ArangoDB Connection error from python

Trying to connect to ArangoDB using python
Code:
from pyArango.connection import *
conn = Connection(username="root", password="XXXXX")
Got below error
Trace:
Traceback (most recent call last):
File "E:/Python/Nlp/imageTotext.py", line 177, in <module>
conn = Connection(username="root", password="XXXXX") File "C:\Users\am843946\AppData\Roaming\Python\Python27\site-packages\pyArango\connection.py",
line 105, in __init__
self.reload() File "C:\Users\am843946\AppData\Roaming\Python\Python27\site-packages\pyArango\connection.py",
line 124, in reload
data = r.json() File "C:\Users\am843946\AppData\Roaming\Python\Python27\site-packages\pyArango\connection.py",
line 19, in __call__
raise e ValueError: No JSON object could be decoded
did you try to specify a connection URL like that?
conn = Connection(arangoURL="http://localhost:8529", username="root", password="")
That way it should work.

Resources