【发布时间】:2020-12-27 13:50:41
【问题描述】:
我有 python 3.7 和 postgresql:
import psycopg2
...
@app.route('/add', methods=['POST'])
def add():
cur = get_db().cursor()
if request.is_json:
jdata = request.get_json()
cur.callproc("add", (jdata['tools'], jdata['ip_begin'], jdata['ip_end']))
result = cur.fetchall()
print(result)
cur.close()
return jsonify({'result': 'add successful'})
else:
cur.close()
return jsonify({'error':"invalid input json data"})
我的店铺功能是:
CREATE FUNCTION "public"."add"("tool_name" varchar, "ip_bgn" inet, "ip_end" inet) RETURNS "pg_catalog"."int8"
$$
DECLARE
mid INTEGER := 0;
ins BIGINT := 0;
BEGIN
if ip_bgn < ip_end then
INSERT into ip_addresses(tool_name, ip_start, ip_end) VALUES (tool_name, ip_bgn, ip_end) RETURNING id into mid;
Loop
if ip_bgn + ins >= ip_end then
exit;
end if;
INSERT into ip_pools(tool_name, ip_address, to_main, status) VALUES(tool_name, ip_bgn+ins, mid, 'free');
ins := ins + 1;
end Loop;
end if;
RETURN ins;
END $$
我的输出是:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
[(11,)] ######################## I have return values
127.0.0.1 - - [28/Dec/2020 00:37:40] "POST /add HTTP/1.1" 200 -
但是当我去数据库时,我发现我的python代码执行后数据库没有添加任何行。
数据库和我之前执行的一样。
我可以使用 plpgsql 控制台通过相同的存储功能创建真实数据。但是如果我通过python代码运行它并不会真正添加行和更改表,但返回数据是可以的。
【问题讨论】:
标签: python postgresql stored-procedures psycopg2