title: Python Flask: werkzeug.exceptions.BadRequestKeyError
body: <p>I am new in Python Flask and I am trying to design my personal blog. Since it is only for private use, I would like to put the &quot;add&quot; page for post as protected area with a username and a password just for to add and manage my posts.
  In order not to show the login credentials in the source code, I decided to store in a .yaml file and retrieve them (<code>{&quot;Franz&quot;:{&quot;pw&quot;:&quot;Biberkopf&quot;}}</code>) through the function login.</p>
  <p>But when I put &quot;Franz&quot; as username and &quot;Biberkopf&quot; as password, I get this error:</p>
  <blockquote>
  <p>werkzeug.exceptions.BadRequestKeyError</p>
  <p>werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.<br />
  KeyError: 'pw'</p>
  <p>Traceback (most recent call last)</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 2464, in <strong>call</strong></p>
  <p>return self.wsgi_app(environ, start_response)</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 2450, in wsgi_app</p>
  <p>response = self.handle_exception(e)</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 1867, in handle_exception</p>
  <p>reraise(exc_type, exc_value, tb)</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_compat.py&quot;, line 39, in reraise</p>
  <p>raise value</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 2447, in wsgi_app</p>
  <p>response = self.full_dispatch_request()</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 1952, in full_dispatch_request</p>
  <p>rv = self.handle_user_exception(e)</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 1821, in handle_user_exception</p>
  <p>reraise(exc_type, exc_value, tb)</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_compat.py&quot;, line 39, in reraise</p>
  <p>raise value</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 1950, in full_dispatch_request</p>
  <p>rv = self.dispatch_request()</p>
  <p>File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 1936, in dispatch_request</p>
  <p>return self.view_functionsrule.endpoint</p>
  <p>File &quot;C:\Users\franc\OneDrive\Desktop\Blog_Project\blog_prova.py&quot;, line 102, in login</p>
  <p>user.id = username<br />
  flask_login.login_user(user)<br />
  return redirect(url_for(&quot;add&quot;))<br />
  else:<br />
  error = &quot;Leider haben Sie die falschen Zugangsdaten.&quot;<br />
  return render_template(&quot;login.html&quot;, error=error)<br />
  return render_template(&quot;login.html&quot;)</p>
  </blockquote>
  <p>Code:</p>
  <pre><code>@app.route('/add')
  
  @login_required
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\templating.py&quot;, line 136, in render_template
  
  ctx.app.update_template_context(context)
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py&quot;, line 838, in update_template_context
  
  context.update(func())
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_login\utils.py&quot;, line 379, in _user_context_processor
  
  return dict(current_user=_get_user())
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_login\utils.py&quot;, line 346, in _get_user
  
  current_app.login_manager._load_user()
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_login\login_manager.py&quot;, line 331, in _load_user
  
  user = self._load_user_from_request(request)
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask_login\login_manager.py&quot;, line 390, in _load_user_from_request
  
  user = self._request_callback(request)
  
  File &quot;C:\Users\franc\OneDrive\Desktop\Blog_Project\blog_prova.py&quot;, line 85, in request_loader
  
      username = request.form.get(&quot;username&quot;)  # comunica col template &lt;input ...name = &quot;username&quot;&gt; Username &lt;/input&gt;
  
      if username not in users:
  
          return
  
      user = User()
  
      user.id = username
  
      user.is_authenticated = request.form[&quot;pw&quot;] == users[username][&quot;pw&quot;]
  
   
  
      return user
  
   
  
   
  
  @app.route('/login', methods=[&quot;POST&quot;, &quot;GET&quot;])
  
  File &quot;C:\Users\franc\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\werkzeug\datastructures.py&quot;, line 442, in __getitem__
  
  raise exceptions.BadRequestKeyError(key)
  
  werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
  KeyError: 'pw'
  </code></pre>
  <p>The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.</p>
  <p>To switch between the interactive traceback and the plaintext one, you can click on the &quot;Traceback&quot; headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.</p>
  <p>You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:</p>
  <pre><code>dump() shows all variables in the frame
  dump(obj) dumps all that's known about the object
  </code></pre>
  <pre><code>
  Edit: If I run the Pycharm debugger, it seems that there are some problems with the method is_authenticated (Property 'is_authenticated' cannot be set). I don´t know if it is somehow inherent.
  
  This is my sample code: 
  
  
  ```
  from datetime import datetime
  import flask_login
  import yaml
  from flask import Flask, render_template, request, redirect, url_for 
  from flask_login import LoginManager, UserMixin, login_required, logout_user
  from flask_sqlalchemy import SQLAlchemy
  
  
  app = Flask(__name__)
  app.config['TESTING'] = False
  app.config['SECRET_KEY'] = 'chiavesegreta'
  app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////Users/Desktop/Blog_Project/blog2.db'
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  db = SQLAlchemy(app)
  
  login_manager = LoginManager()
  login_manager.init_app(app)
  
  
  # {&quot;Franz&quot;:{&quot;pw&quot;:&quot;Biberkopf&quot;}}
  with open(r'C://Users//Desktop//application.yaml') as file:
      users = yaml.full_load(file)
  
  
  class User(UserMixin):
      pass
  
  
  class Blogpost2(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      title = db.Column(db.String(50))
      subtitle = db.Column(db.String(50))
      author = db.Column(db.String(20))
      date_posted = db.Column(db.DateTime)
      content = db.Column(db.Text)
  
  db.create_all()
  
  
  @app.route('/')
  def index():
      posts = Blogpost2.query.order_by(Blogpost2.date_posted.desc()).all()
  
      return render_template('index.html', posts=posts)
  
  
  @app.route('/about')
  def about():
      return render_template('about.html')
  
  
  @app.route('/post/&lt;int:post_id&gt;')
  def post(post_id):
      post = Blogpost2.query.filter_by(id=post_id).one() 
  
      date_posted = post.date_posted.strftime('%d %B, %Y')
  
      return render_template('post.html', post=post, date_posted=date_posted)
  
  
  @login_manager.user_loader
  def user_loader(username):
      if username not in users:
          return
  
      user = User()
      user.id = username
      return user
  
  
  @login_manager.request_loader
  def request_loader(request):
      username = request.form.get(&quot;username&quot;)  
      if username not in users:
          return
      user = User()
      user.id = username
      user.is_authenticated = request.form[&quot;pw&quot;] == users[username][&quot;pw&quot;]
  
      return user
  
  
  @app.route('/login', methods=[&quot;POST&quot;, &quot;GET&quot;])
  def login():
      error = None
      if request.method == 'POST':
          username = request.form.get('username')
          if request.form.get('pw') == users[username][&quot;pw&quot;]:
              user = User()
              user.id = username
              flask_login.login_user(user)
              return redirect(url_for(&quot;add&quot;))
          else:
              error = &quot;Leider haben Sie die falschen Zugangsdaten.&quot;
              return render_template(&quot;login.html&quot;, error=error)
      return render_template(&quot;login.html&quot;)
  
  
  @app.route('/add')
  @login_required
  def add():
      return render_template('add.html')
  
  
  @app.route('/logout')
  def logout():
      logout_user()
      return &quot;Logged out !&quot;
  
  
  
  @app.route('/contact')
  def contact():
      return render_template('contact.html')
  
  
  @app.route('/prova')
  def prova():
      return render_template('prova.html')
  
  
  @app.route('/addpost', methods=['POST'])
  def addpost():
      title = request.form['title']
      subtitle = request.form['subtitle']
      author = request.form[&quot;author&quot;]
      content = request.form['content']
  
      post = Blogpost2(title=title, subtitle=subtitle, author=author, content=content, date_posted=datetime.now())
  
      db.session.add(post)
      db.session.commit()
  
      return redirect(url_for('index'))
  
  
  if __name__ == &quot;__main__&quot;:
      app.run(debug=True)
  
  
  </code></pre>
  <p>The idea would be that, if someone tries to log in without the right username and password, an error message would be displayed. With the right credentials you can have access to the &quot;add&quot; page. Here my login.html page:</p>
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html lang=&quot;en&quot;&gt;
  
  &lt;head&gt;
  
    &lt;meta charset=&quot;utf-8&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;author&quot; content=&quot;&quot;&gt;
  
    &lt;title&gt;Clean Blog - Start Bootstrap Theme&lt;/title&gt;
  
    &lt;!-- Bootstrap core CSS --&gt;
    &lt;!-- &lt;link href=&quot;vendor/bootstrap/css/bootstrap.min.css&quot; rel=&quot;stylesheet&quot;&gt; --&gt;
    &lt;link href= &quot;{{ url_for('static', filename='bootstrap.min.css')}}&quot; rel=&quot;stylesheet&quot;&gt;
  
    &lt;!-- Custom fonts for this template --&gt;
    &lt;!--  &lt;link href=&quot;vendor/fontawesome-free/css/all.min.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;                              --&gt;
    &lt;link href=&quot;{{url_for('static', filename = 'fontawesome.min.css')}}&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot;&gt;
    &lt;link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'&gt;
    &lt;link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'&gt;
  
    &lt;!-- Custom styles for this template --&gt;
    &lt;link href=&quot;{{url_for('static', filename = 'clean-blog.min.css')}}&quot; rel=&quot;stylesheet&quot;&gt;
  
  &lt;/head&gt;
  
  &lt;body&gt;
  
     &lt;!-- Navigation --&gt;
    &lt;nav class=&quot;navbar navbar-expand-lg navbar-light fixed-top&quot; id=&quot;mainNav&quot;&gt;
      &lt;div class=&quot;container&quot;&gt;
        &lt;a class=&quot;navbar-brand&quot; href= &quot;{{ url_for('index') }}&quot;&gt;Start Bootstrap&lt;/a&gt;
        &lt;button class=&quot;navbar-toggler navbar-toggler-right&quot; type=&quot;button&quot; data-toggle=&quot;collapse&quot; data-target=&quot;#navbarResponsive&quot; aria-controls=&quot;navbarResponsive&quot; aria-expanded=&quot;false&quot; aria-label=&quot;Toggle navigation&quot;&gt;
          Menu
          &lt;i class=&quot;fas fa-bars&quot;&gt;&lt;/i&gt;
        &lt;/button&gt;
        &lt;div class=&quot;collapse navbar-collapse&quot; id=&quot;navbarResponsive&quot;&gt;
          &lt;ul class=&quot;navbar-nav ml-auto&quot;&gt;
            &lt;li class=&quot;nav-item&quot;&gt;
              &lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for('index')}}&quot;&gt;Home&lt;/a&gt;
            &lt;/li&gt;
            &lt;li class=&quot;nav-item&quot;&gt;
              &lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for('about')}}&quot;&gt;About&lt;/a&gt;
            &lt;/li&gt;
            &lt;li class=&quot;nav-item&quot;&gt;
              &lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for('contact')}}&quot;&gt;Contact&lt;/a&gt;
            &lt;/li&gt;
            &lt;li class=&quot;nav-item&quot;&gt;
              &lt;a class=&quot;nav-link&quot; href=&quot;{{ url_for('prova')}}&quot;&gt;Prova&lt;/a&gt;
            &lt;/li&gt;
          &lt;/ul&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/nav&gt;
  
    &lt;!-- Page Header --&gt;
    &lt;header class=&quot;masthead&quot; style=&quot;background-image: url('img/contact-bg.jpg')&quot;&gt;
      &lt;div class=&quot;overlay&quot;&gt;&lt;/div&gt;
      &lt;div class=&quot;container&quot;&gt;
        &lt;div class=&quot;row&quot;&gt;
          &lt;div class=&quot;col-lg-8 col-md-10 mx-auto&quot;&gt;
            &lt;div class=&quot;page-heading&quot;&gt;
              &lt;h1&gt;Login&lt;/h1&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/header&gt;
  
  
  
    &lt;hr&gt;
  
    &lt;!-- Footer --&gt;
    &lt;footer&gt;&lt;!-- Main Content --&gt;
    &lt;div class=&quot;container&quot;&gt; &lt;!-- crea contenitore x la larghezza del layout --&gt;
      &lt;div class=&quot;row&quot;&gt; &lt;!--  crea riga  --&gt;
        &lt;div class=&quot;col-lg-8 col-md-10 mx-auto&quot;&gt; &lt;!-- crea colonna --&gt;
          &lt;p&gt;Login zu dem privaten Area dieses Blogs&lt;/p&gt;
  
          &lt;form action = &quot;&quot; method = &quot;POST&quot; name=&quot;sentMessage&quot; id=&quot;contactForm&quot; novalidate&gt;
            &lt;div class=&quot;control-group&quot;&gt;
              &lt;div class=&quot;form-group floating-label-form-group controls&quot;&gt;
  
                &lt;label&gt;Username&lt;/label&gt;
  
                   &lt;input name = &quot;username&quot; type=&quot;text&quot; class=&quot;form-control&quot; placeholder=&quot;Username&quot; id=&quot;Username&quot; required data-validation-required-message=&quot;Please enter your username.&quot; value =&quot;{{ request.form.username }}&quot;&gt;
                   &lt;p class=&quot;help-block text-danger&quot;&gt;&lt;/p&gt;
                  &lt;/div&gt;
                 &lt;/div&gt;
            &lt;div class=&quot;control-group&quot;&gt;
              &lt;div class=&quot;form-group floating-label-form-group controls&quot;&gt;
                &lt;label&gt;Password&lt;/label&gt;
  
                &lt;input name= &quot;pw&quot;  class=&quot;input&quot; placeholder=&quot;pw&quot; id=&quot;pw&quot; required data-validation-required-message=&quot;Please enter your password.&quot; value = &quot;{{ request.form.pw }}&quot;&gt;
  
                &lt;p class=&quot;help-block text-danger&quot;&gt;&lt;/p&gt;
              &lt;/div&gt;
            &lt;/div&gt;
  
            &lt;div class = &quot;container&quot;&gt;
            &lt;div class = &quot;row&quot; &gt;
            &lt;input type = &quot;checkbox&quot; onclick = &quot;Toggle()&quot;&gt;
  
                &lt;label&gt; Show Password &lt;/label&gt;
  
              &lt;script&gt;
  
                  function Toggle() {
                  var temp = document.getElementById(&quot;typepass&quot;);
                  if (temp.type === &quot;password&quot;) {
                  temp.type = &quot;text&quot;;
                }
                  else {
                    temp.type = &quot;password&quot;;
                  }
  
                }
  
              &lt;/script&gt;
  
            &lt;/div&gt;
          &lt;/div&gt;
  
  
  
  
  
            &lt;br&gt;
            &lt;div id=&quot;success&quot;&gt;&lt;/div&gt;
            &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot; id=&quot;sendMessageButton&quot;&gt;Login!&lt;/button&gt;
          &lt;/form&gt;
  
          {% if error %}
  
          &lt;p class = &quot;error&quot;&gt; &lt;strong&gt; Error: &lt;/strong&gt; {{ error }}
  
            {% endif %}
  
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
      &lt;div class=&quot;container&quot;&gt;
        &lt;div class=&quot;row&quot;&gt;
          &lt;div class=&quot;col-lg-8 col-md-10 mx-auto&quot;&gt;
            &lt;!-- Qua inizia la parte inferiore--&gt;
            &lt;p class=&quot;copyright text-muted&quot;&gt;Copyright &amp;copy; Your Website 2020&lt;/p&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/footer&gt;
  
  
  
    &lt;!-- Bootstrap core JavaScript --&gt;
    &lt;script src= &quot;{{ url_for('static', filename = 'jquery.min.js')}}&quot;&gt; &lt;/script&gt;
    &lt;script src= &quot;{{ url_for('static', filename = 'bootstrap.min.js')}}&quot;&gt;&lt;/script&gt;
  
  
    &lt;!-- Custom scripts for this template --&gt;
    &lt;script src=&quot;{{ url_for('static', filename = 'clean-blog.min.js')}}&quot;&gt; &lt;/script&gt;&gt;
  
  &lt;/body&gt;
  
  &lt;/html&gt;
  </code></pre>
  <p>I am very new to everything and I am pretty stuck and confused at the moment. Thank you very much for every suggestion.</p>