错误请求浏览器(或代理)发送了此服务器无法理解的请求

时间:2018-01-12 07:13:47

标签: python postgresql flask

我已经尝试填充add.html,当我点击发送时,我得到上面的错误。 错误请求 浏览器(或代理)发送了此服务器无法理解的请求。 我的app.py如下。

from flask import Flask, render_template, url_for, redirect, request

from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import requests

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://user:mypassword@localhost/mydb' 

db=SQLAlchemy(app)
# class User(db.Model):
#     id = db.Column(db.Integer, primary_key=True)
#     username = db.Column(db.String(80), unique=True, nullable=False)
#     email = db.Column(db.String(120), unique=True, nullable=False)

#     def __init__(self , username, email):
#         self.username = username
#         self.email = email

#     def __repr__(self):
#         return '<User %r>' % self.username

class Blogpost(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(50))
    date=db.Column(db.DateTime)
    content=db.Column(db.Text)



@app.route('/')
def index():
    return render_template('index.html')


@app.route('/about')
def about():
    return render_template('about.html')


@app.route('/post')
def post():
    return render_template('post.html')


@app.route('/contact')
def contact():
    return render_template('contact.html')

@app.route('/add')
def add():
    return render_template('add.html')

@app.route('/addpost', methods=['POST'])
def addpost():
    if request.method=='POST':

        title = request.form['title']
        subtitle = request.form['subtitle']
        author = request.form['author']
        date = request.form['date']
        content = request.form['content']
        post=Blogpost(title=title, subtitle=subtitle, author=author, date_posted=datetime.now(), content=content)

       db.session.add(post)
       db.session.commit()

    return redirect(url_for('index'))



if __name__ == '__main__':
    app.run(debug=True)


#And below is my is my add.html file
<!DOCTYPE html>
<html lang="en">

  <head>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Clean Blog - Start Bootstrap Theme</title>

     <!-- Bootstrap core CSS -->
    <link href="{{url_for('static', filename='bootstrap.min.css')}}" rel="stylesheet">

    <!-- Custom fonts for this template -->
    <link href="{{url_for('static', filename='font-awesome.min.css')}}" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <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'>

    <!-- Custom styles for this template -->
    <link href="{{url_for('static', filename='clean-blog.min.css')}}" rel="stylesheet">

  </head>

  <body>

    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
      <div class="container">
        <a class="navbar-brand" href="{{('/')}}">Start Bootstrap</a>
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu
          <i class="fa fa-bars"></i>
        </button>
        <div class="collapse navbar-collapse" id="navbarResponsive">
          <ul class="navbar-nav ml-auto">
            <li class="nav-item">
              <a class="nav-link" href="{{('/')}}">Home</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{{('/about')}}">About</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{{('/post')}}">Sample Post</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="{{('/contact')}}">Contact</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>

    <!-- Page Header -->
    <header class="masthead" style="background-image: url('{{url_for('static', filename='contact-bg.jpg')}}')">
      <div class="overlay"></div>
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">
            <div class="page-heading">
              <h1>Create a new blogpost</h1>
              <span class="subheading">You can create a new blogpost here</span>
            </div>
          </div>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-md-10 mx-auto">

          <form name="addForm" id="addForm" name="addForm" method="POST" action="{{url_for('addpost')}}" novalidate>
            <div class="control-group">
              <div class="form-group floating-label-form-group controls">
                <label>Title</label>
                <input type="text" class="form-control" placeholder="title" id="title" name="title" required data-validation-required-message="Please enter a title.">
                <p class="help-block text-danger"></p>
              </div>
            </div>
            <div class="control-group">
              <div class="form-group floating-label-form-group controls">
                <label>Sub-title</label>
                <input type="email" class="form-control" placeholder="subtitle" name="subtitle" id="subtitle" required data-validation-required-message="Please enter your Sub-title.">
                <p class="help-block text-danger"></p>
              </div>
            </div>
            <div class="control-group">
              <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Author</label>
                <input type="tel" class="form-control" placeholder="author" name="author" id="author" required data-validation-required-message="Your Name.">
                <p class="help-block text-danger"></p>
              </div>
            </div>
              <div class="control-group">
            <div class="control-group">
              <div class="form-group floating-label-form-group controls">
                <label>Post</label>
                <textarea rows="5" class="form-control" placeholder="content" name="content" id="name" required data-validation-required-message="Please enter content."></textarea>
                <p class="help-block text-danger"></p>
              </div>
            </div>
            <br>
            <div id="success"></div>
            <div class="form-group">
              <button type="submit" class="btn btn-primary" id="sendMessageButton">Send</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <hr>

    <!-- Footer -->
        <footer>
      <div class="container">
        <div class="row">
          <div class="col-lg-8 col-md-10 mx-auto">
            <ul class="list-inline text-center">
            </ul>
            <p class="copyright text-muted">Copyright &copy; Your Website 2017</p>
          </div>
        </div>
      </div>
    </footer>
    <!-- Bootstrap core JavaScript -->
    <script src="{{url_for('static', filename='jquery.min.js')}}"></script>
    <script src="{{url_for('static', filename='bootstrap.bundle.min.js')}}"></script>

    <!-- Contact Form JavaScript -->
    <script src="{{url_for('static', filename='jqBootstrapValidation.js')}}"></script>
    <script src="{{url_for('static', filename='contact_me.js')}}"></script>



    <!-- Custom scripts for this template -->
    <script src="{{url_for('static', filename='clean-blog.min.js')}}"></script>

  </body>

</html>

当我在填写表单后尝试提交时,我收到错误:

错误请求 浏览器(或代理)发送了此服务器无法理解的请求。

我尝试在文件上输出它,但我仍然收到错误

1 个答案:

答案 0 :(得分:0)

我通过添加

调试了这个
import pdb; pdb.set_trace()
请求方法检查后立即

addpost()。事实证明,date = request.form['date']指令失败,因为表单上没有日期:

(Pdb) request
<Request 'http://localhost:5000/addpost' [POST]>
(Pdb) request.form
ImmutableMultiDict([('content', u'asdfasdfasdfasdf'), ('title', u'asdfasdf'), ('subtitle', u'adsfasdfasdf'), ('author', u'asdfasdfasdf')])
(Pdb) request.form['title']
u'asdfasdf'
(Pdb) request.form['date']
*** BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

删除date = request.form['date']后,错误消失。