Escaping a string before inserting/updating with PyMongo

Hallo,
How i can Escaping a String before i use them for inserts / updates.
Is this possible with PyMongo.

Did you try this?

str = """hello "lovely" world"""
print str
hello "lovely" world

Thats not my problem.
i have a code like this
collection.find({ “type”: var })
But now when a user post a bad code like this
var = "{ “$gte”: “” } "
how I can escape the var variable to prevent for bad code injection.

Check the string for dollar characters and/or curly braces and reject that input.

>>> s = "asdfg${"
>>> "$" in s or "{" in s
True
>>>
1 Like

As long as you’re building up your query as a dict then you don’t need to escape values in your query. Having a quote or a curly brace inside your string is safe - there’s no parser to get confused with your query string, like can happen with a SQL query. In this case, your query is just a dict so the values are safe - providing you don’t run eval on any strings coming from your user!

If you’re building your query by concatenating strings together, then you’d need to escape parts of the string - but that’s bad practice and I recommend you avoid it altogether.

2 Likes

Just to clarify using the example above:

var = "{ '$gte': '' }"
collection.find({ "type": var })

is equivalent to:

collection.find({ "type": "{ '$gte': '' }" })

So we are trying to find documents where "type" is equal to the string "{ '$gte': '' }" there is no risk of injection here as it is a string and not a dict

As @Mark_Smith mentions, this would only become a problem if you somehow convert the string into a dict. @Mark_Smith mentioned eval, but I would also be careful when using json.loads, or any parser which can convert a string into a Python object

2 Likes