前面写了两篇文章,结果错误不少,经过修正,改了很多错误
1 跨域
加上以下两条
from flask_cors import CORS
from flask_cors import cross_origin
以下让整个全景跨域
CORS(app, supports_credentials=True)
2 secret_key
加上secret_key 防止session 报错
app.secret_key='kdjklfjkd87384hjdhjh'
3 接收python 数据
@app.route('/project/add', methods=['POST'])
def add_entry():
#if not session.get('logged_in'):
# abort(401)
print("data recv !!!!!!!!!!!!!!!!!!!!!!")
data=request.get_data()
print("data recv 2!!!!!!!!!!!!!!!!!!!!!!")
data = data.decode('utf-8')
data=json.loads(data)
print("data recv 3!!!!!!!!!!!!!!!!!!!!!!")
pname = data.get('projectname')
num= data.get('projectname')
memo = data.get('memo')
g.db.execute('insert into project(projectname,picnum,memo) values (?,?,?)',
# [request.form['projectname'], request.form['picnum'],request.form['memo'] ])
[pname,num,memo])
g.db.commit()
flash('New project was successfully posted')
return "{'ret':ok}"
其中需要data.decode 去解码utf-8 编码,去掉前面的 b 这个多余的字节。
4 改成非develop
去掉flask develop的警告
server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
server.serve_forever()
这样要把gevent装上
pip install gevent
5 发送端测试
发送端使用以前的代码,注意的是:发送的时候写上 json = data,不要写成 data = data,以前我的写法是错误的。文章来源:https://www.toymoban.com/news/detail-565015.html
import json
import requests
import time
headers = {'Content-Type': 'application/json'}
data = {
"projectname":"four screen",
"picnum":8,
"memo":"test"
}
try:
r = requests.post("http://127.0.0.1:5000/project/add", json=data, headers=headers)
print(r.text)
except requests.exceptions.ConnectionError:
print('connectionError')
time.sleep(1)
6 代码清单
以下代码清单错误减去了不少,数据库增加数据正常
服务端和测试客户端正常
文章来源地址https://www.toymoban.com/news/detail-565015.html
from __future__ import with_statement
from contextlib import closing
import sqlite3
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash,jsonify
from flask_cors import CORS
from flask_cors import cross_origin
import json
from gevent import pywsgi
# configuration
DATABASE = './project.db'
DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
app.secret_key='kdjklfjkd87384hjdhjh'
CORS(app, supports_credentials=True)
def connect_db():
return sqlite3.connect(app.config['DATABASE'])
def init_db():
with closing(connect_db()) as db:
with app.open_resource('db.sql',"r") as f:
#str = f.read()
#print(str)
db.cursor().executescript(f.read())
db.commit()
@app.before_request
def before_request():
g.db = connect_db()
@app.after_request
def after_request(response):
g.db.close()
return response
@app.route('/')
def show_first():
return "this is a test"
@app.route('/project', methods=['GET'])
def show_project():
cur = g.db.execute('select id,projectname,picnum,memo,created from project order by id desc')
entries = [dict(id=row[0], projectname=row[1],picnum= row[2],memo=row[3],created=row[4]) for row in cur.fetchall()]
return jsonify(entries)
@app.route('/project/add', methods=['POST'])
def add_entry():
#if not session.get('logged_in'):
# abort(401)
print("data recv !!!!!!!!!!!!!!!!!!!!!!")
data=request.get_data()
print("data recv 2!!!!!!!!!!!!!!!!!!!!!!")
#get_Data = get_Data.decode('utf-8')
data = data.decode('utf-8')
data=json.loads(data)
print("data recv 3!!!!!!!!!!!!!!!!!!!!!!")
pname = data.get('projectname')
num= data.get('projectname')
memo = data.get('memo')
g.db.execute('insert into project(projectname,picnum,memo) values (?,?,?)',
# [request.form['projectname'], request.form['picnum'],request.form['memo'] ])
[pname,num,memo])
g.db.commit()
flash('New project was successfully posted')
return "{'ret':ok}"
#return redirect(url_for('show_first'))
@app.route('/project/del/<id>', methods=['POST'])
#@cross_origin(supports_credentials=True)
def del_entry():
#if not session.get('logged_in'):
# abort(401)
g.db.execute('delete from project where id = ?',[id])
g.db.commit()
flash('project was successfully delete')
return redirect(url_for('show_first'))
#需要登录或者单点登录的时候把以下代码准备加上
@app.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_first'))
return render_template('login.html', error=error)
#需要登录或者单点登录的时候把以下代码准备加上
@app.route('/logout')
def logout():
session.pop('logged_in', None)
flash('You were logged out')
return redirect(url_for('show_first'))
if __name__ == '__main__':
init_db()
server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
server.serve_forever()
到了这里,关于python flask server 接收post数据注意的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!