I am playing around with Flask. I have created an API using Flask-Restful and Flask-JWT. When Debug=True in Flask, and I do not send the Authorization Header, I get the response as However, when the debug=False, the response returned is Internal Server Error with this stack trace,
[2017-01-19 19:43:10,753] ERROR in app: Exception on /api_0_1/deals [GET]
Traceback (most recent call last):
File "C:\Users\ARFATS~1\Desktop\Dealflow\venv\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\ARFATS~1\Desktop\Dealflow\venv\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\ARFATS~1\Desktop\Dealflow\venv\lib\site-packages\flask_restful\__init__.py", line 477, in wrapper
resp = resource(*args, **kwargs)
File "C:\Users\ARFATS~1\Desktop\Dealflow\venv\lib\site-packages\flask_jwt\__init__.py", line 176, in decorator
_jwt_required(realm or current_app.config['JWT_DEFAULT_REALM'])
File "C:\Users\ARFATS~1\Desktop\Dealflow\venv\lib\site-packages\flask_jwt\__init__.py", line 155, in _jwt_required
headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})
JWTError: Authorization Required. Request does not contain an access token
I would like Flask-JWT to respond with the response which is there when Debug=True. However, I cannot use debug on Production servers. One way is to use my own jwt_required decorator. Is there any other way?Also, I would be happy to know what I am missing, if any. Thanks
You will need to add this setting to your flask app:
app.config['PROPAGATE_EXCEPTIONS'] = True
When debug is true, PROPAGATE_EXCEPTIONS is also set to true by default.
Perhaps consider checking out flask-jwt-extended instead (https://github.com/vimalloc/flask-jwt-extended), it takes care of the PROPAGATE_EXCEPTIONS for you. It aims to replace the abandoned flask-jwt library, and add some conviences when working with JWTs (such as refresh tokens, easily adding custom data to the JWTs, fresh vs non-fresh tokens, and more). Full disclosure, I'm the author of that extension.
Cheers.
Related
I went on Google Cloud and enabled a project, billing, and the Cloud Speech to Text API. Then I downloaded a .json file. Then I tried to execute this basic code in PyCharm.
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] ="instant-medium-282.json"
from google.cloud import speech_v1
from google.cloud.speech_v1 import enums
client = speech_v1.SpeechClient()
encoding = enums.RecognitionConfig.AudioEncoding.FLAC
sample_rate_hertz = 44100
language_code = 'en-US'
config = {'encoding': encoding, 'sample_rate_hertz': sample_rate_hertz, 'language_code': language_code}
uri = 'gs://bucket_name/file_name.flac'
audio = {'uri': uri}
response = client.recognize(config, audio)
However, I keep getting this error:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
return callable_(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/grpc/_channel.py", line 826, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.PERMISSION_DENIED
details = "The billing account for the owning project is disabled in state absent"
debug_error_string = "{"created":"#1593884707.640503000","description":"Error received from peer ipv6:[2607:f8b0:4009:813::200a]:443","file":"src/core/lib/surface/call.cc","file_line":1055,"grpc_message":"The billing account for the owning project is disabled in state absent","grpc_status":7}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/sal.py", line 16, in <module>
response = client.recognize(config, audio)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/google/cloud/speech_v1/gapic/speech_client.py", line 255, in recognize
return self._inner_api_calls["recognize"](
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
return wrapped_func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/google/api_core/retry.py", line 281, in retry_wrapped_func
return retry_target(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/google/api_core/retry.py", line 184, in retry_target
return target()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
return func(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/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.PermissionDenied: 403 The billing account for the owning project is disabled in state absent
I also confirmed with Google Cloud customer support that billing is enabled as it should be. Any suggestions on how to fix this error?
I ran into an issue while uploading a file using the CLI where I was trying to copy into a bucket that did not actually exist. It threw this same error "AccessDeniedException: 403 The billing account for the owning project is disabled in state closed".
If all was well with billing, perhaps the bucket you were pointing to did not exist?
Just wanted to flag that there seem to be non-billing reasons for such an error could be thrown..
The "The billing account for the owning project is disabled in state absent" error message,may happen when the API has just been enabled recently. So it is recommended to try again.
In my case,
"AccessDeniedException: 403 The billing account for the owning project is disabled in state closed"
happen, because I didn't added 'Billing Account' to the project I've created.
You can link your project to a Billing Account in Billing Projects tab.
Once you did so, wait some time and the error should gone.
I have been trying to get the Elasticsearch to work in a Django application. It has been a problem because of the mess of compatibility considerations this apparently involves. I follow the recommendations, but still get an error when I actually perform a search.
Here is what I have
Django==2.1.7
Django-Haystack==2.5.1
Elasticsearch(django)==1.7.0
Elasticsearch(Linux app)==5.0.1
There is also DjangoCMS==3.7 and aldryn-search=1.0.1, but I am not sure how relevant those are.
Here is the error I get when I submit a search query via the basic text form.
GET /videos/modelresult/_search?_source=true [status:400 request:0.001s]
Failed to query Elasticsearch using '(video)': TransportError(400, 'parsing_exception')
Traceback (most recent call last):
File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/haystack/backends/elasticsearch_backend.py", line 524, in search
_source=True)
File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/client/utils.py", line 69, in _wrapped
return func(*args, params=params, **kwargs)
File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/client/__init__.py", line 527, in search
doc_type, '_search'), params=params, body=body)
File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/transport.py", line 307, in perform_request
status, headers, data = connection.perform_request(method, url, params, body, ignore=ignore, timeout=timeout)
File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/connection/http_urllib3.py", line 93, in perform_request
self._raise_error(response.status, raw_data)
File "/home/user-name/miniconda3/envs/project-web/lib/python3.7/site-packages/elasticsearch/connection/base.py", line 105, in _raise_error
raise HTTP_EXCEPTIONS.get(status_code, TransportError)(status_code, error_message, additional_info)
elasticsearch.exceptions.RequestError: TransportError(400, 'parsing_exception')
Could someone tell me if this is an issue with compatibility or is there something else going on? How can I fix it?
The combination that appears to have worked for my setup is as follows. I believe the key was to drastically downgrade the Elasticsearch.
Elasticsearch=1.7.6 (with Java 8)
Django==2.1.7
Django-Haystack==2.8.1
elasticsearch==1.7.0
The two items below may or may not be relevant. I have not changed them.
DjangoCMS==3.7.0
aldryn-search==1.0.1
I am a django newbie, and I inherited a django back-end with little documentation. I am making a request to said server, which is hosted on AWS. To store the files in the request we use S3.
I have found nothing on the django code that limits the size of the file uploads, and I suspect it may be AWS closing the connection because of file size.
This is the code I use, and below the error I get whenever the total size of the files is over 1 MB:
import requests
json_dict = {'key_1':'value_1','video':video,'image':,image}
requests.post('https://api.test.whatever.io/v1/register', json=dict_reg)
video is a video file ('.mov','.avi','.mp4',etc) with base64 encoding, and image is an image file ('.jpg','.png') with base64 encoding.
And this is the trace I get, ONLY when the total size is over 1 MB:
/usr/local/lib/python2.7/dist-
packages/requests/packages/urllib3/util/ssl_.py:132: InsecurePlatfo
rmWarning: A true SSLContext object is not available. This prevents urllib3
from configuring SSL
appropriately and may cause certain SSL connections to fail. You can upgrade
to a newer version of Python to solve this. For more information, see
https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecurePlatformWarningTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 110, in
post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 56, in
request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line
488, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line
609, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line
473, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(32,
'Broken pipe'))
As mentioned previously, I have not found anywhere in the django code a limit to the file size, any hints where I should be looking at?
I also did not find anything on the AWS S3 policy.
Assuming you have a Nginx to reverse proxy your HTTP requests? if yes check this link.
Also see the value set for the below value in settings for the Upload Handlers in django
FILE_UPLOAD_MAX_MEMORY_SIZE
In the end it was the nginx configuration. changing the variable client_max_body_size in the nginx.conffile from 1M to 2M did the trick.
I have made a webapp in python using web2py which has 3rd party authentication using Janrain as recommended.
On my local server it worked absolutely fine, but now when I deployed on pythonanywhere, the authentication is giving me the following error
"class 'urllib2.URLError' urlopen error Tunnel connection failed: 403 Forbidden"
Stack
===========
File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/usr/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/usr/lib/python2.7/urllib2.py", line 1222, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/usr/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
URLError: <urlopen error Tunnel connection failed: 403 Forbidden>
==========================
For third party authentication I had used yahoomail id.
This has now been fixed, but in case anyone else comes across this issue or a similar issue:
the problem was that free users on PythonAnywhere have restricted internet, that goes via a proxy and only allows a whitelist of sites.
The sites .janrain.com and .rpxnow.com weren't on the whitelist at the time, but we have now added them, and the janrain/yahoo mail login now works.
So, for anyone else that happens to be going via a proxy and trying to use this service, those are the sites you need to add. (may also be of interest to paranoid people that like to run noscript, if you find some federated auth system failing, you may need to unblock rpxnow).
Happy coding everyone!
We've got a Django-based web application that is used for receiving POST data from iOS devices (push notification tokens).
All in all, the application seems to be working fine, and we're receiving a 1000-2000 POSTs with valid data every hour. However, I'm occasionally receiving error logs from Django with the following data:
Traceback (most recent call last):
File "/opt/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/opt/local/lib/python2.7/site-packages/django/views/decorators/vary.py", line 19, in inner_func
response = func(*args, **kwargs)
File "/opt/local/lib/python2.7/site-packages/django_piston-0.2.3-py2.7.egg/piston/resource.py", line 160, in __call__
request.data = request.POST
File "/opt/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 180, in _get_post
self._load_post_and_files()
File "/opt/local/lib/python2.7/site-packages/django/http/__init__.py", line 372, in _load_post_and_files
self._post, self._files = QueryDict(self.body, encoding=self._encoding), MultiValueDict()
File "/opt/local/lib/python2.7/site-packages/django/http/__init__.py", line 328, in body
self._body = self.read()
File "/opt/local/lib/python2.7/site-packages/django/http/__init__.py", line 384, in read
return self._stream.read(*args, **kwargs)
File "/opt/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 98, in read
result = self.buffer + self._read_limited()
File "/opt/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 92, in _read_limited
result = self.stream.read(size)
UnreadablePostError: request data read error
And the WSGIRequest dump says POST: <could not parse>
I've been trying to find more information on this error, and a lot of what I'm seeing points to this error being caused by a user canceling a POST request before the post completes. Is this an error that I should be concerned about, or should I just set up the server to filter out these error messages? I'd say that I get maybe 8-10 automated emails per day about this.
I'm not sure whether you're still waiting for the answer but basically the comments contain most of the information. So, just to close the question up...
These errors mean that a malformed request arrived to the server. Someone might have cancelled their request or it got mangled on its way (e.g. bad internet connection), etc.
You can't solve these errors directly. However you can take a look at the page (if it's always the same one) and check if for example the loading doesn't take too long. You can also try and cause the error manually to see when exactly it happens and why. Unless you find something relevant, I don't think you need to worry about it much.