Is "cgi.escape" necessary in a Python application?
Question: Was looking over a developer's code. He did something that I have never seen
before in a Python application. His background is in PHP and is just learning
python, so I don't know if this is perhaps a holdover from the different
system architectures that he is used to working with.

He told me that the purpose of this code is to prevent the user from attacking
the application via code insertion. I'm pretty sure this is unnecessary for
our use case since we are never evaluating the data as code, but I just wanted
to make sure and ask the community.

    
    
    # Import library
    from cgi import escape
    
    # Get information that the client submitted
    fname   = GET_request.get('fname',   [''] )[0]
    
    # Make sure client did not submit malicious code <- IS THIS NECESSARY?
    if fname:
        fname = escape(fname)
    

  * Is this typically necessary in a Python application? 
  * In what situations is it necessary? 
  * In what situations is it not necessary?


Answer: If user input is going into a database, or anywhere else it might be executed,
then code injection could be a problem.

[This](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-
injection?lq=1) question asks about ways to prevent code injection in php, but
the principle is the same - SQL queries containing malicious code get
executed, potentially doing things like deleting all your data.

The [escape](http://docs.python.org/2/library/cgi.html#cgi.escape) function
converts <, > and & characters into html-safe sequences.

From those two links it doesn't look like escape() is enough on it's own, but
something does need to be done to stop malicious code. Of course this may well
be being taken care of elsewhere in your code.

