bdnome = collection.find_one({ $text: {$search: vername}})
At this line a error appears in "$text" with the following error
"unexpected token '$'" and "unexpected toke 'text', and a error
appears in "$search" --- "unexpected token '{'" and "unexpected
token '$'" and "unexpected token 'search'", and a error occurs
as well in "vername" --- "unexpected token 'vername".
I'm working with databases in MongoDB
You are trying to use JavaScript syntax in Python. That doesn't work.
bdnome = collection.find_one({ "$text": {"$search": vername}})
Related
I have a small python code in which I am using exception handling.
def handler(event):
try:
client = boto3.client('dynamodb')
response = client.scan(TableName=os.environ["datapipeline_table"])
return response
except Exception as error:
logging.exception("GetPipelinesError: %s",json.dumps(error))
raise GetPipelinesError(json.dumps({"httpStatus": 400, "message": "Unable to fetch Pipelines"}))
class GetPipelinesError(Exception):
pass
pylint warning gives me " Consider explicitly re-raising using the 'from' keyword ".
I saw few other posts, where they used from and raised an error. I made modifications like this
except Exception as GetPipelinesError:
logging.exception("GetPipelinesError: %s",json.dumps(GetPipelinesError))
raise json.dumps({"httpStatus": 400, "message": "Unable to fetch Pipelines"}) from GetPipelinesError
Is this the right way to do ?
No. The purpose of raise-from is to chain exceptions. The correct syntax in your case is:
except Exception as error:
raise GetPipelinesError(json.dumps(
{"httpStatus": 400, "message": "Unable to fetch Pipelines"})) from error
The expressions that follow raise and from must be exception classes or instances.
So, I have the following view function in connexion (I am trying to work on a Open APIV3 project):
def my_view_func_in_python():
return_dict = {"status": False, "stdout": None, "stderr": None}
try:
payload = connexion.request.get_json()
json_data = payload["json"]
fileName = payload["fileName"]
text_lines = []
for line in json_data["res"][0]["lines"]:
text_lines.append(line["text"])
text = " ".join(text_lines)
os.remove("./assets/request.jpg")
return_dict.update([
("status", True)
])
except BaseException as ex:
return_dict.update([
("stderr", ex)
])
return return_dict
Now for some reason, if I give an empty json field value via swagger, the code breaks in the line which has for loop for line in json_data["res"][0]["lines"]. But if it breaks, it should go in the except line and return the return_dict peacefully. But what it returns me is a 500 error on swagger.
SWAGGER OUTPUT:
{
"detail": "The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.",
"status": 500,
"title": "Internal Server Error",
"type": "about:blank"
}
and, what error it throws me in the backend where I have hosted the app:
TypeError: Object of type 'KeyError' is not JSON serializable
I have tried alot of places, open apiv3 specs, swagger documentation and connexion documentation. I am not able to just catch this error! What can I do?
I'm trying to handle for errors when users are signing up or logging in to my app. The first error I'm trying to handle for is when a user tries to create an account with an email that already exists in the database. I get the following HTTPError:
requests.exceptions.HTTPError: [Errno 400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=] {
"error": {
"code": 400,
"message": "EMAIL_EXISTS",
"errors": [
{
"message": "EMAIL_EXISTS",
"domain": "global",
"reason": "invalid"
}
]
}
}
I want to access the "message": "EMAIL_EXISTS" value in the below but I'm not sure how to do it. I've added the below code but that produces the following error:
error_message = error["error"]["message"]
TypeError: 'HTTPError' object is not subscriptable
import requests
import pyrebase
class CreateAccount():
def create_account(self):
try:
auth.create_user_with_email_and_password(self.email, self.password)
except requests.exceptions.HTTPError as error:
print(error)
error_message = error["error"]["message"]
print(error_message)
After much searching I've found an answer to this problem:
except requests.HTTPError as e:
error_json = e.args[1]
error = json.loads(error_json)['error']['message']
if error == "EMAIL_EXISTS":
print("Email already exists")
I've tried the code you provided in comment which I couldn't make to work. Maybe a version issue of requests module or something else.
However, the code below works in my case:
except requests.exceptions.HTTPError as e:
error_json = e.args[1]
error = json.loads(error_json)['error']['message']
if error == "EMAIL_EXISTS":
print("Email already exists")
Yeah, requests.exceptions.HTTPError instead of requests.HTTPError.
Is there a way to customise a Boto3 Lambda exception message in the form of a HTTP response and return it while also sending a forced failed?
Here is an example
except Exception as e:
print ('\nException : failed to invoke jobs.')
print ('Error : ' + str(e) + '\n')
return {
'statusCode': 500,
'body': 'Exception : failed to invoke EMR jobs'
}
So the customised message is now returned but the Lambda still returns a job success rather than failure.
In order to send the job failure the exception block can be changed to -
except Exception as e:
print ('\nException : failed to invoke jobs.')
print ('Error : ' + str(e) + '\n')
raise
But now the custom error message has been lost.
Is there a way to combine the custom response error message and to fail the Lambda job?
To get the custom error message as output for the lambda, you need to actually raise the exception with the custom error message.
except Exception as e:
custom_error = '\nException : failed to invoke jobs.\n'
custom_error += 'Error : ' + str(e) + '\n'
raise Exception(custom_error)
And you will get an error message like:
{
"errorMessage": "Exception : failed to invoke jobs. ....",
"stackTrace": [
[
"/var/task/lambda_function.py",
3,
"my_always_fails_handler",
"raise Exception(custom_error)"
]
],
"errorType": "Exception"
}
You can find more on the AWS documentation that you can find here Python exceptions in lambdas
You didn't mention it, but you're probably using AWS API Gateway to in front of your lambda.
You can use API Gateway "integration response" to transform your failed result to the HTTP response.
Here's a link to the docs
I'm using rest framework's Token authentication for my api. Recently I've found an issue that, If the Token provided in the request is invalid, instead of returning Invalid Token response, django throws TypeError at /api/users/: 'exceptions.KeyError' object is not callable.
I checked on the trace, and found this:
In django/db/models/query.py(Django version=1.7) file line no 357, inside raise DoesNotExists exception call, the actual exception TypeError raised by self.model._meta.object_name.
if num == 1:
return clone._result_cache[0]
if not num:
raise self.model.DoesNotExist(
"%s matching query does not exist." %
self.model._meta.object_name)
Does anybody knows why model's object_name became exception.KeyError rather than Token?
Bizarrely, I got this when I had this line in my code:
except KeyError, models.MyModel.DoesNotExist:
where the comma was interpreted as "as", redefining models.MyModel.DoesNotExist as a KeyError and causing "exception.KeyError is not callable" when creating one.
What I meant to do was:
except (KeyError, models.MyModel.DoesNotExist):