Request Method Recursion Issue - python

The request dot get method is not working properly.
currently, I am using Python 3.8.10. Before it was working fine but now it happens the issue.
please find the code and error message below for reference.
Code
x = requests.get('https://w3schools.com', timeout=10)
print(x.status_code)
Error:
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python3.8/dist-packages/flask/app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/root/api-server/server/rest.py", line 141, in getprice
data = General().getprice()
File "/usr/local/lib/python3.8/dist-packages/flask_caching/__init__.py", line 795, in decorated_function
rv = f(*args, **kwargs)
File "/root/api-server/server/methods/general.py", line 41, in getprice
result = utils.getprice()
File "/root/api-server/server/utils.py", line 180, in getprice
x = requests.get('https://api.widecoin.org/info', timeout=10)
File "/usr/local/lib/python3.8/dist-packages/requests/api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 530, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.8/dist-packages/requests/sessions.py", line 643, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/requests/adapters.py", line 439, in send
resp = conn.urlopen(
File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 665, in urlopen
httplib_response = self._make_request(
File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 376, in _make_request
self._validate_conn(conn)
File "/usr/local/lib/python3.8/dist-packages/urllib3/connectionpool.py", line 994, in _validate_conn
conn.connect()
File "/usr/local/lib/python3.8/dist-packages/urllib3/connection.py", line 368, in connect
self.ssl_context = create_urllib3_context(
File "/usr/local/lib/python3.8/dist-packages/urllib3/util/ssl_.py", line 273, in create_urllib3_context
context.options |= options
File "/usr/lib/python3.8/ssl.py", line 602, in options
super(SSLContext, SSLContext).options.__set__(self, value)
File "/usr/lib/python3.8/ssl.py", line 602, in options
super(SSLContext, SSLContext).options.__set__(self, value)
File "/usr/lib/python3.8/ssl.py", line 602, in options
super(SSLContext, SSLContext).options.__set__(self, value)
[Previous line repeated 476 more times]
RecursionError: maximum recursion depth exceeded

Related

Call Celery Inspect from Django fails on every 2 requests with a "not enough values to unpack (expected 2, got 1)"

I am calling the following code from a django view (taken from https://docs.celeryq.dev/en/latest/userguide/workers.html#inspecting-workers):
inspect_report = celery_app.control.inspect()
tasks_active = inspect_report.active()
It works correctly the first time but when I refresh the page i get a ValueError: not enough values to unpack (expected 2, got 1)
Stacktrace:
File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 458, in thread_handler
raise exc_info[1]
File "/venv_path/python3.9/site-packages/django/core/handlers/exception.py", line 38, in inner
response = await get_response(request)
File "/venv_path/python3.9/site-packages/django/core/handlers/base.py", line 233, in _get_response_async
response = await wrapped_callback(request, *callback_args, **callback_kwargs)
File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 423, in __call__
ret = await asyncio.wait_for(future, timeout=None)
File "/home/benjamin/.pyenv/versions/3.9.6/lib/python3.9/asyncio/tasks.py", line 442, in wait_for
return await fut
File "/venv_path/python3.9/site-packages/asgiref/current_thread_executor.py", line 22, in run
result = self.fn(*self.args, **self.kwargs)
File "/venv_path/python3.9/site-packages/asgiref/sync.py", line 462, in thread_handler
return func(*args, **kwargs)
File "/venv_path/python3.9/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func
response = view_func(request, *args, **kwargs)
File "/venv_path/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/benjamin/project/administration/views.py", line 357, in dashboard
tasks_active = inspect_report.active()
File "/venv_path/python3.9/site-packages/celery/app/control.py", line 149, in active
return self._request('active', safe=safe)
File "/venv_path/python3.9/site-packages/celery/app/control.py", line 106, in _request
return self._prepare(self.app.control.broadcast(
File "/venv_path/python3.9/site-packages/celery/app/control.py", line 741, in broadcast
return self.mailbox(conn)._broadcast(
File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 344, in _broadcast
return self._collect(reply_ticket, limit=limit,
File "/venv_path/python3.9/site-packages/kombu/pidbox.py", line 386, in _collect
self.connection.drain_events(timeout=timeout)
File "/venv_path/python3.9/site-packages/kombu/connection.py", line 317, in drain_events
return self.transport.drain_events(self.connection, **kwargs)
File "/venv_path/python3.9/site-packages/kombu/transport/virtual/base.py", line 969, in drain_events
get(self._deliver, timeout=timeout)
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 526, in get
ret = self.handle_event(fileno, event)
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 508, in handle_event
return self.on_readable(fileno), self
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 504, in on_readable
chan.handlers[type]()
File "/venv_path/python3.9/site-packages/kombu/transport/redis.py", line 905, in _brpop_read
dest, item = dest__item
ValueError: not enough values to unpack (expected 2, got 1)
3rd page call is OK, 4th give same error, etc.
Why does it fail every 2 requests?

django-cities-light ValueError: invalid literal for int() with base 10: ''

I am getting error when I run python manage.py cities_light
here is the complete error
Assuming local download is up to date for http://download.geonames.org/export/dump/countryInfo.txt
Traceback (most recent call last):
File "manage.py", line 30, in <module>
execute_from_command_line(sys.argv)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/core/management/base.py", line 364, in execute
output = self.handle(*args, **options)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/cities_light/management/commands/cities_light.py", line 215, in handle
self.country_import(items)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/cities_light/management/commands/cities_light.py", line 308, in country_import
country = Country.objects.get(geoname_id=items[ICountry.geonameid])
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 399, in get
clone = self.filter(*args, **kwargs)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 892, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1290, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1315, in _add_q
child_clause, needed_inner = self.build_filter(
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1251, in build_filter
condition = self.build_lookup(lookups, col, value)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup
lookup = lookup_class(lhs, rhs)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/lookups.py", line 20, in __init__
self.rhs = self.get_prep_lookup()
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/lookups.py", line 70, in get_prep_lookup
return self.lhs.output_field.get_prep_value(self.rhs)
File "/home/khalid/Desktop/file whersk/wherks-web/env/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1825, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: ''
You should pay attention to this.
This problem has been considered and is still open, but there is already a solution.
pip install git+https://github.com/yourlabs/django-cities-light.git#master
This should help.

ValueError generic WSGI request error too many values to unpack (expected 2)

I am running a flask application, to which I am getting an OPTIONS call, on the following URL,
/test//
The correct domain name is /test/user-name/. But somehow the username is missing in the options call.
The above scenario results in my application to break.
The traceback is as follows:
Traceback (most recent call last):
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/serving.py", line 323, in run_wsgi
execute(self.server.app)
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/serving.py", line 312, in execute
application_iter = app(environ, start_response)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 2464, in __call__
return self.wsgi_app(environ, start_response)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_request_id_header/middleware/__init__.py", line 51, in __call__
return self.app(environ, new_start_response)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/api/wsgi_application.py", line 664, in _nr_wsgi_application_wrapper_
result = _WSGIApplicationMiddleware(wrapped,
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/api/wsgi_application.py", line 192, in __init__
self.iterable = self.application(self.request_environ,
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 2450, in wsgi_app
response = self.handle_exception(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_restful/__init__.py", line 269, in error_router
return original_handler(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 108, in _nr_wrapper_Flask_handle_exception_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1867, in handle_exception
reraise(exc_type, exc_value, tb)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_cors/extension.py", line 161, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
File "/home/company/Documents/project/lib/python3.8/site-packages/flask_restful/__init__.py", line 269, in error_router
return original_handler(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 108, in _nr_wrapper_Flask_handle_exception_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1816, in handle_user_exception
return self.handle_http_exception(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 90, in _nr_wrapper_Flask_handle_http_exception_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/lib/python3.8/site-packages/flask/app.py", line 1744, in handle_http_exception
return handler(e)
File "/home/company/Documents/project/lib/python3.8/site-packages/newrelic/hooks/framework_flask.py", line 126, in _nr_wrapper_error_handler_
return wrapped(*args, **kwargs)
File "/home/company/Documents/project/service/app/code_service.py", line 81, in page_not_found
return Response(
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/wrappers/base_response.py", line 187, in __init__
self.headers = Headers(headers)
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/datastructures.py", line 958, in __init__
self.extend(defaults)
File "/home/company/Documents/project/lib/python3.8/site-packages/werkzeug/datastructures.py", line 1101, in extend
for key, value in iter_multi_items(args[0]):
ValueError: too many values to unpack (expected 2) | line-113 |
Kindly help me figure out the fix for this. Here is the link to the app.py file.
https://github.com/shubhamkumar0/medilink/blob/master/app.py
Thanks in Advance!
The response header was being passed as a set, which I changed to map and the issue got resolved. Thanks for your time.

How to send jwt token in json format?

I'm trying to figure out API with python. And want to send back some already encrypted jwt token.
When I'm trying to return jwt token in return method sends back Error's and Error's page in postman app shows up. But when printing it inside console everything works fine.
class Login(Resource):
def post(self):
json_data = request.get_json(force=True)
un = json_data['username']
pw = json_data['password']
encoded_jwt = jwt.encode({'username': un, 'password': pw}, 'OH HI MARK', algorithm='HS256')
print(encoded_jwt)
return jsonify(token = encoded_jwt)
I'm excpecting to get this token `
b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImhpIiwicGFzc3dvcmQiOiJwYXNzd29yZCJ9.MQ-hwWabt13E4KMFxPztSUr6RYwsZZ-tT0sdv2s0vU0'
But getting bunch of error.
Edit:
Asked to add Error's.
Traceback (most recent call last):
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 269, in error_router
return original_handler(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\_compat.py", line 34, in reraise
raise value.with_traceback(tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 269, in error_router
return original_handler(e)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\_compat.py", line 34, in reraise
raise value.with_traceback(tb)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask_restful\__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "D:\FinallySomethingWork\Yeah\app.py", line 16, in post
return jsonify(token = encoded_jwt)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 321, in jsonify
dumps(data, indent=indent, separators=separators) + '\n',
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 179, in dumps
rv = _json.dumps(obj, **kwargs)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 201, in encode
chunks = list(chunks)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "D:\FinallySomethingWork\venv\lib\site-packages\flask\json\__init__.py", line 81, in default
return _json.JSONEncoder.default(self, o)
File "C:\Users\Denis\AppData\Local\Programs\Python\Python37-32\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
The error message says:
TypeError: Object of type bytes is not JSON serializable
That means, encoded_jwt is a byte array which can't be serialized into a JSON.
You first have to convert it to a string:
return jsonify(token = encoded_jwt.decode("utf-8"))
On a sidenote: don't put the password into the token!

Python - unhashable type error in urllib2

>> url = 'https://test.authorize.net/gateway/transact.dll'
>> data = {'x_login': 'abc123', 'x_type': 'AUTH_CAPTURE', 'x_card_num': '4444333322221103', 'x_amount': '50.75', 'x_tran_key
': 'abc123', 'x_version': '3.1', 'x_delim_char': '|', 'x_exp_date': '022012', 'x_delim_data': 'TRUE'}
>>
>> urllib2.urlopen(url, data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gateways\base.py", line 81, in dispatch
return gw_method(self, *args, **kwargs)
File "gateways\decorators.py", line 17, in wrapper
method(*args, **kwargs)
File "gateways\authorize_net.py", line 39, in auth_capture
return self.post_data(data)
File "gateways\authorize_net.py", line 43, in post_data
raw_response = urllib2.urlopen(self.get_endpoint(), data)
File "C:\Python26\lib\urllib2.py", line 124, in urlopen
return _opener.open(url, data, timeout)
File "C:\Python26\lib\urllib2.py", line 389, in open
response = self._open(req, data)
File "C:\Python26\lib\urllib2.py", line 407, in _open
'_open', req)
File "C:\Python26\lib\urllib2.py", line 367, in _call_chain
result = func(*args)
File "C:\Python26\lib\urllib2.py", line 1154, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "C:\Python26\lib\urllib2.py", line 1118, in do_open
h.request(req.get_method(), req.get_selector(), req.data, headers)
File "C:\Python26\lib\httplib.py", line 898, in request
self._send_request(method, url, body, headers)
File "C:\Python26\lib\httplib.py", line 938, in _send_request
self.send(body)
File "C:\Python26\lib\httplib.py", line 743, in send
self.sock.sendall(str)
File "C:\Python26\lib\ssl.py", line 203, in sendall
v = self.send(data[count:])
TypeError: unhashable type
I can't figure out what caused this error.
data is suppossed to be a "a buffer in the standard application/x-www-form-urlencoded format.", not a dict.
Before you pass the data dict in do data = urllib.urlencode(data), so you get the correct format from your dict.
You can also use the following if you are using json.
json.dumps(data)
Remember: urlencode can encode a dict, but not a string. The output of json.dumps is a string.

Categories