gpt4 book ai didi

python - 如何修复 {"message": "The method is not allowed for the requested URL." } for my post method?

转载 作者:行者123 更新时间:2023-12-01 08:04:46 26 4
gpt4 key购买 nike

这是我第一次为 android 改造创建 API。我根据网上得到的代码片段修改了这段代码。 post方法的主要功能是获取给定的参数并将其存储在sqlite3数据库中。

我的以下两个表的架构:

sqlite> .schema spending
CREATE TABLE spending(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT ,
reason TEXT ,
amount INTEGER
);

CREATE TABLE receiving(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT ,
from_reason TEXT ,
amount INTEGER
);
from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask import jsonify

db_connect = create_engine('sqlite:///api.db')
app = Flask(__name__)
api = Api(app)

class AddSpending(Resource):
def add_spending(self):
try:
_json = request.json
_date = _json['date']
_reason = _json['reason']
_amount = _json['amount']
# validate the received values
if _date and _reason and _amount and request.method == 'POST':
#do not save password as a plain text
#_hashed_password = generate_password_hash(_password)
# save edits
sql = "INSERT INTO spending(date, reason, amount) VALUES(%s, %s, %d)"
data = (_date, _reason, _amount)
#conn = mysql.connect()
conn = db_connect.connect()
cursor = db_connect.cursor()
conn.cursor()
conn.execute(sql, data)
conn.commit()
#resp = jsonify('Spending added successfully!')
#resp.status_code = 200
return
else:
return 404
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()

api.add_resource(AddSpending, '/spending_up',methods=['POST']) # Route_3

当用户通过此参数传递数据时。数据应存储在数据库中

最佳答案

我认为问题在于您将方法称为 add_spending 并应命名为 post

def add_spending(self)更改为def post(self)

您的 api 代码应如下所示,没有 methods='POST'

class AddSpending(Resource):
def post(self):
try:
_json = request.json
_date = _json['date']
_reason = _json['reason']
_amount = _json['amount']
# validate the received values
if _date and _reason and _amount and request.method == 'POST':
#do not save password as a plain text
#_hashed_password = generate_password_hash(_password)
# save edits
sql = "INSERT INTO spending(date, reason, amount) VALUES(%s, %s, %d)"
data = (_date, _reason, _amount)
#conn = mysql.connect()
conn = db_connect.connect()
cursor = db_connect.cursor()
conn.cursor()
conn.execute(sql, data)
conn.commit()
#resp = jsonify('Spending added successfully!')
#resp.status_code = 200
return
else:
return 404
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()

api.add_resource(AddSpending, '/spending_up') # Route_3

更新

我刚刚尝试了与您类似的代码并成功了

enter image description here

另一个更新

您的 repo 代码

enter image description here

关于python - 如何修复 {"message": "The method is not allowed for the requested URL." } for my post method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55592040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com