我连接到现有的postgreSQL数据库并尝试使用post方法向表中添加新值。所以,我的代码看起来像这样:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import render_template, request, redirect, url_for
app = Flask(__name__)
POSTGRES = {
'user': 'postgres',
'pw': 'postgres',
'db': 'In',
'host': 'localhost',
'port': '5432',
}
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\
%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES
db = SQLAlchemy(app)
class User(db.Model):
key = db.Column(db.VARCHAR, primary_key=True)
place_name = db.Column(db.VARCHAR(100))
admin_name1 = db.Column(db.VARCHAR(100))
latitude = db.Column(db.NUMERIC(9, 6))
longitude = db.Column(db.NUMERIC(9, 6))
def __init(self, key, place_name, admin_name1, latitude, longitude):
self.key = key
self.place_name = place_name
self.admin_name1 = admin_name1
self.latitude = latitude
self.longitude = longitude
@app.route('/')
def index():
return render_template('add_location.html')
@app.route('/post_location', methods=['POST'])
def post_location():
user = User(request.form['key'], request.form['palce_name'],
request.form['admin_name1'], request.form['latitude'],
request.form['longitude'])
db.session.add(user)
print user
db.session.commit()
return redirect(url_for('index'))
if __name__ == '__main__':
app.run()
这是我的add_location.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title></title>
<head>
<body>
<form method="post" action="/post_location">
<label>Pin:</label>
<input type="text" name="key" />
<label>City:</label>
<input type="text" name="place_name" />
<label>Address:</label>
<input type="text" name="admin_name1" />
<label>Lat:</label>
<input type="text" name="latitude" />
<label>Long:</label>
<input type="text" name="longitude" />
<input type="submit">
</form>
</body>
</html>
一切似乎都很好,但我仍然收到错误的请求错误。是因为我的postgresql表的数据类型与代码不匹配。
答案 0 :(得分:2)
功能post_location()
中的拼写错误,palce
中的request.form['palce_name']
字应为place
。
Flask会处理客户端错误等问题,因此您获得了400。
答案 1 :(得分:0)
我遇到了这个问题,我的问题是我试图以 Flask 似乎无法理解的方式 POST
一个文件。我是这样做的:
<input type="file" id="fileEl"/>
// Incorrect:
let response = await fetch("http://example.com/upload", {
method: "POST",
body: fileEl.files[0],
}).then(r => r.json());
当 Flask 似乎希望文件作为表单数据时:
// Correct:
let formData = new FormData();
formData.append("file", fileEl.files[0]);
let response = await fetch("http://example.com/upload", {
method: "POST",
body: formData,
}).then(r => r.json());