title: Flask Preventing Form Injection
body: <p><strong>How can python / flask block foreign form injections?</strong></p>
  
  <p>Consider the following mwe:</p>
  
  <p>app.py</p>
  
  <pre><code>from flask import Flask, request, render template
  
  app = Flask(__name__)
  
  @app.route('/', methods=['GET','POST'])
  def helloworld():
      if request.method == 'GET':
          return render_template('index.html') 
      if request.method == 'POST':
          print(request.form['info'])
  
          ## do something with the info, like write to a database
  
          return 'nothing'
  
  if __name__ == '__main__':
      app.run(debug=True)
  </code></pre>
  
  <p>templates/index.html</p>
  
  <pre><code>&lt;html&gt;
  &lt;head&gt;
  &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script type='text/javascript' src="{{ url_for('static', filename='js/fire.js') }}"&gt;&lt;/script&gt;
  &lt;/head&gt;
  
  &lt;body&gt;
  &lt;p&gt;Hello world!&lt;/p&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>static/js/fire.js</p>
  
  <pre><code>$(document).click(function() {
  
      // post data to flask
  
      $.post('/', {'info': 'test'});
  
      return false;
  
  };
  </code></pre>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Is injection possible from a foreign website? Follow-up: how could this be done? (e.g., perhaps via a form that posts to my website url?)</li>
  <li>If injection is possible, what can I do in the app.py script to block the injection?</li>
  </ol>
  
  <h1>Edit</h1>
  
  <p>Here is a very basic script that can be used to test injections against the above flask application. The accepted answer blocks this script:</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;body&gt;
  
  &lt;h2&gt;Malicious Form Injection&lt;/h2&gt;
  
  &lt;form action='http://127.0.0.1:5000/' method='post'&gt;
    Input 1:&lt;br&gt;
    &lt;input name="info" value="mal1"&gt;&lt;br&gt;
    &lt;input type="submit" value="Submit"&gt;
  &lt;/form&gt;
  
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>