AttributeError: __enter__ in pyopenssl 20.0.1 - websocket

When creating a secure websocket connection(wss) using websocket create_connection() api call in pyopenssl - openssl/ssl.py (20.0.1), AttributeError: enter error is thrown.
Error is pointing to "with statements available in send method of SSL.py file" whereas in 19.1.0 pyopenssl version, there was no error observed.
with _from_buffer(buf) as data:
# check len(buf) instead of len(data) for testability
if len(buf) > 2147483647:
raise ValueError(
"Cannot send more than 2**31-1 bytes at once."
)
result = _lib.SSL_write(self._ssl, data, len(data))
self._raise_ssl_error(self._ssl, result)
return result

Try pip install pyOpenSSL==19.1.0

Related

Paho on_connect works if connection OK but is not called when error. Why?

Why does my paho-mqtt (1.5.1) on_connect work if connection OK but it is not called when an error. For testing I'm using Linux Lite 4.2 based on Ubuntu 18.04 LTS with Xfcs running in a VM (VBox).
class subscribemqtt:
.....
def on_connect(self, client, userdata, flags, rc):
print ("ZZZZZZZZZZZZZ in on_connect")
connectErrs = {.........}
self.connectRc = rc
self.connectReason = connectErrs[str(rc)]
print ("$$$$$$$$$$$$$", self.connectRc, self.connectReason)
return
def subscribe(self, arguments):
...........
self.client = paho.Client(self.config['CLIENT_ID'])
self.client.on_message = self.on_subscribe
self.client.on_connect = self.on_connect
print ("#############", self.on_connect)
print ("XXXXXXXXXXXX calling self.client.connect(...)
self.client.connect(self.config['HOST'],self.config['PORT'])
print ("YYYYYYYYYYYYY calling self.client.loop_start()")
self.client.loop_start()
print ("AAAAAAAAAAAAA", self.connected)
while not self.connected:
time.sleep(0.1)
print ("BBBBBBBBBBBBB", self.connected, self.connectRc)
When all the parameters are correct, on_connect gets called:
############# <bound method subscribemqtt.on_connect of <__main__.subscribemqtt object at 0x7f32065a6ac8>>
XXXXXXXXXXXX calling self.client.connect(self.config['HOST'],self.config['PORT']
YYYYYYYYYYYYY calling self.client.loop_start()
AAAAAAAAAAAAA**ZZZZZZZZZZZZZ in on_connect**
False$$$$$$$$$$$$$
0 Connection successful
BBBBBBBBBBBBB True 0
When I set the host address to an invalid address (to create an error to test my error handling) I get:
subscribemqtt.subscribe:topic= Immersion Dummy
############# <bound method subscribemqtt.on_connect of <__main__.subscribemqtt object at 0x7ffb942ae0b8>>
XXXXXXXXXXXX calling self.client.connect(self.config['HOST'],self.config['PORT']
Traceback (most recent call last):
File "/home/linuxlite/Desktop/EMS/sendroutines/subscribemqtt.py", line 275, in <module>
(retcode, reason, topic) = subscribeObj.subscribe([None, topic])
File "/home/linuxlite/Desktop/EMS/sendroutines/subscribemqtt.py", line 191, in subscribe
self.client.connect(self.config['HOST'],self.config['PORT'])
File "/usr/local/lib/python3.6/dist-packages/paho/mqtt/client.py", line 941, in connect
return self.reconnect()
File "/usr/local/lib/python3.6/dist-packages/paho/mqtt/client.py", line 1075, in reconnect
sock = self._create_socket_connection()
File "/usr/local/lib/python3.6/dist-packages/paho/mqtt/client.py", line 3546, in _create_socket_connection
return socket.create_connection(addr, source_address=source, timeout=self._keepalive)
File "/usr/lib/python3.6/socket.py", line 704, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
>>>
Thanks for reading.
Alan
PS. I just tried:
try:
self.client.connect(self.config['HOST'],self.config['PORT'])
except:
print ("**************** Error exception calling self.client.connect")
And that works but my understanding is that on_connect should be called for errors.
From the docs:
on_connect()
on_connect(client, userdata, flags, rc)
Called when the broker responds to our connection request.
The important part there is "when the broker responds". But in the example you have shown the hostname provided can not be resolved, so broker never responds because it is never actually contacted.
on_connect() will be called if connection succeeds or if it fails because the username/password is wrong or a unavailable protocol version (e.g. requesting MQTTv5 from a broker that only supports v3)

How could I resolve xmlrpc.client.Fault while trying to search a package through pip3? [duplicate]

I am getting this error in pip search while studying python.
The picture is an error when I pip search. Can you tell me how to fix it?
$ pip search pdbx
ERROR: Exception:
Traceback (most recent call last):
File "*/lib/python3.7/site-packages/pip/_internal/cli/base_command.py", line 224, in _main
status = self.run(options, args)
File "*/lib/python3.7/site-packages/pip/_internal/commands/search.py", line 62, in run
pypi_hits = self.search(query, options)
File "*/lib/python3.7/site-packages/pip/_internal/commands/search.py", line 82, in search
hits = pypi.search({'name': query, 'summary': query}, 'or')
File "/usr/lib/python3.7/xmlrpc/client.py", line 1112, in __call__
return self.__send(self.__name, args)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1452, in __request
verbose=self.__verbose
File "*/lib/python3.7/site-packages/pip/_internal/network/xmlrpc.py", line 46, in request
return self.parse_response(response.raw)
File "/usr/lib/python3.7/xmlrpc/client.py", line 1342, in parse_response
return u.close()
File "/usr/lib/python3.7/xmlrpc/client.py", line 656, in close
raise Fault(**self._stack[0])
xmlrpc.client.Fault: <Fault -32500: 'RuntimeError: This API has been temporarily disabled due to unmanageable load and will be deprecated in the near future. Please use the Simple or JSON API instead.'>
The pip search command queries PyPI's servers, and PyPI's maintainers have explained that the API endpoint that the pip search command queries is very resource intensive and too expensive for them to always keep open to the public. Consequently they sometimes throttle access and are actually planning to remove it completely soon.
See this GitHub issues thread ...
The solution I am using for now is to pip install pip-search (a utility created by GitHub user #victorgarric).
So, instead of 'pip search', I use pip_search. Definitely beats searching PyPI via a web browser
Follow the suggestion from JRK at the discussion at github (last comment) the search command is temporarily disabled, use your browser to search for packages meanwhile:
Check the thread on github and give him a thumb up ;)
search on website, https://pypi.org/,
then install the package you wanted
The error says
Please use the Simple or JSON API instead
You can try pypi-simple to query the pip repository
https://pypi.org/project/pypi-simple/
It gives an example too, I tried to use it here:
pypi-simple version 0.8.0 DistributionPackage' object has no attribute 'get_digest':
!/usr/bin/env python3
-*- coding: utf-8 -*-
"""
Created on Thu Nov 11 17:40:03 2020
#author: Pietro
"""
from pypi_simple import PyPISimple
def simple():
package=input('\npackage to be checked ')
try:
with PyPISimple() as client:
requests_page = client.get_project_page(package)
except:
print("\n SOMETHING WENT WRONG !!!!! \n\n",
"CHECK INTERNET CONNECTION OR DON'T KNOW WHAT HAPPENED !!!\n")
pkg = requests_page.packages[0]
print(pkg)
print(type(pkg))
print('\n',pkg,'\n')
print('\n'+pkg.filename+'\n')
print('\n'+pkg.url+'\n')
print('\n'+pkg.project+'\n')
print('\n'+pkg.version+'\n')
print('\n'+pkg.package_type+'\n')
#print('\n'+pkg.get_digest()+'\n','ENDs HERE !!!!') #wasnt working
if __name__ == '__main__':
simple()
got -4 so far for this answer don't know why , figureout I can try to check for a package with:
# package_name = input('insert package name : ')
package_name = 'numpy'
import requests
url = ('https://pypi.org/pypi/'+package_name+'/json')
r = requests.get(url)
try:
data = r.json()
for i in data:
if i == 'info':
print('ok')
for j in data[i]:
if j == 'name':
print((data[i])[j])
print([k for k in (data['releases'])])
except:
print('something went south !!!!!!!!!!')

I cant understand this syntax error in AWS lambda, while writing lambda for stopping a ecs task in a service

- import json
import boto3
client = boto3.client('ecs')
def lambda_handler(event, context):
return {
response = client.stop_task(
cluster='newCluster',
task='d3a857b8f2e1463d85265e08b6dfd9f3',
reason='none'
)
}
I have written this lambda, but when I test it , it shows syntax error like below
Response:
{
"errorMessage": "Syntax error in module 'lambda_function': invalid syntax (lambda_function.py, line 8)",
"errorType": "Runtime.UserCodeSyntaxError",
"stackTrace": [
" File "/var/task/lambda_function.py" Line 8\n response = client.stop_task(\n"
]
}
Request ID:
"9cb74885-0171-4ed9-9e6f-44e50480139b"
Function Logs: START RequestId: 9cb74885-0171-4ed9-9e6f-44e50480139b
Version: $LATEST [ERROR] Runtime.UserCodeSyntaxError: Syntax error in
module 'lambda_function': invalid syntax (lambda_function.py, line 8)
Traceback (most recent call last):   File
"/var/task/lambda_function.py" Line 8
           response = client.stop_task( END RequestId: 9cb74885-0171-4ed9-9e6f-44e50480139b REPORT RequestId:
9cb74885-0171-4ed9-9e6f-44e50480139b Duration: 27.35 ms Billed
Duration: 100 ms Memory Size: 128 MB Max Memory Used: 56 MB Init
Duration: 108.01 ms XRAY TraceId:
1-5d846522-6de3bafd93f9f6ddd732c151 SegmentId:
5c86ef0b79d59359 Sampled: false
Worth removing the response or return just the response for testing just check by removing it and then tidy up the code later.
return {
client.stop_task(cluster='newCluster',task='d3a857b8f2e1463d85265e08b6dfd9f3',reason='none')
}
Or worth doing something like this other wise the response is going to be unreachable.
response = client.stop_task(
cluster='newCluster',
task='d3a857b8f2e1463d85265e08b6dfd9f3',
reason='none')
return response
Its Worth using the ARN for task and cluster and check how it works docs attached
This is how i have used it in my working code, reason being optional.(here i have just substituted the values for that variable here for explanation)
client.stop_task(
cluster='arn:aws:ecs:us-east-1:xxxxxxxxxxxx:cluster/dev',
task='arn:aws:ecs:us-east-1:xxxxxxxxxxxx:task/1de5e17a-422a-4ac4-a493-371970d6d4d6')
import json
import boto3
client = boto3.client('ecs')
def lambda_handler(event, context):
response=client.stop_task(cluster='newCluster',task='d3a857b8f2e1463d85265e08b6dfd9f3',reason='none')
I just removed the return and its braces and it worked.

How to print Graphene-Django / Graphene-Python Exceptions to the Console for Debugging?

When a GraphQL Error occurs, I cannot easily know where it occured. I have to spend unnecessary time trying to track it down. How do I get a Traceback printed in the console of my text editor?
I answered my own question by accessing the GraphQL error(s) with result.errors, iterating through the list, and using python's print_tb function to print the Traceback.
Does anyone have a different or better way of doing it?
Example usage of the print_graphql_errors function:
from django.conf.settings import DEBUG
result = schema.execute(
mutation_str, context_value=request, variable_values=variable_values
)
if result.errors is None:
return self.handle_success(result)
if DEBUG:
print_graphql_errors(result.errors)
return self.handle_failure(result)
The print_graphql_errors function:
from traceback import print_tb
from django.conf.settings import DEBUG
def print_graphql_errors(errors, raise_error=False):
if not DEBUG:
raise Exception(
'DevError: This function should not be called in production'
)
assert errors, 'DevError: The "errors" parameter cannot be None'
print_after = []
current_error = None
print('######################################################################')
print('Manually Generated Traceback (with the print_graphql_errors function):')
print(f'There are {len(errors)} errors:')
for i, error in enumerate(errors):
print(f'{i + 1}) ', error)
print('######################################################################')
for error in errors:
current_error = error
# FYI: This object has these attributes: (example attribute values)
# tb_frame <frame at 0x000002DDB844D548, file 'site-packages\\graphql\\execution\\executor.py', line 455, code resolve_or_error>
# tb_lasti 16
# tb_lineno 447
# tb_next <traceback object at 0x000002DDBAFBA388>
# print('error.locations:', error.locations)
# print('error.positions:', error.positions)
try:
print_tb(error.stack)
except AttributeError as e:
print(e.__traceback__)
print(f'Warning: An error occured while trying to print the traceback: {e}. It has the following attributes instead: {dir(error)}')
print_after.append(error)
if len(print_after):
print('###################################################################')
print(f'Number of errors without the "stack" attribute: {len(print_after)}')
print('###################################################################')
if raise_error:
for error in print_after:
raise error
raise current_error

How can I use scrapy to fetch the data through proxy, at the same time I do not use middlewares

I am using scrapy to fetch the data, I bought some proxies. I read the scrapy doc, I found that if I want to use proxy, I should write middlewares. Now my question is how can I use proxy without middlewares? I tried like this:
def start_requests(self):
name = my_name
password = password
proxy = my proxy
return[
FormRequest(url,formate={'account':my_name,'password':password},
meta={'proxy':proxy},
callback=self.after_login)
]
def after_login(self, response):
response.xpath(.....)
I got TypeError:argument of type 'NoneType' is not iterable
Here is the Traceback:
Traceback (most recent call last):
File "/home/think/sjs-project/sjs/venv/local/lib/python2.7/site-packages/twisted/internet/endpoints.py", line 542, in connect
timeout=self._timeout, bindAddress=self._bindAddress)
File "/home/think/sjs-project/sjs/venv/local/lib/python2.7/site-packages/twisted/internet/posixbase.py", line 482, in connectTCP
c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
File "/home/think/sjs-project/sjs/venv/local/lib/python2.7/site-packages/twisted/internet/tcp.py", line 1165, in __init__
if abstract.isIPv6Address(host):
File "/home/think/sjs-project/sjs/venv/local/lib/python2.7/site-packages/twisted/internet/abstract.py", line 522, in isIPv6Address
if '%' in addr:
TypeError: argument of type 'NoneType' is not iterable
What am I doing wrong? Thanks very much.

Resources