gpt4 book ai didi

python - 如何从Put路由和Delete的url获取ID

转载 作者:行者123 更新时间:2023-12-01 09:29:58 25 4
gpt4 key购买 nike

我试图将所有 CRUD 方法放在 Python Tornado 框架中的一个处理程序类下。 Post()get() 可以工作,但由于某种原因无法定义 carId。我可以将 api 端点的 id 传递给该方法的一种方法是什么?放置和删除的端点:api/cars/1

Error: TypeError: put() missing 1 required positional argument:
'carId' ERROR:tornado.access:500 PUT /api/cars/1 (::1) 0.50ms

方法:

    # Delete method that deletes data specified by HTTP client from database
def delete(self, carId):

try:
data = json.loads(self.request.body)
print(data)
print("Deleting Car")
id = data["id"]
if not carId:
return self.write({"success": False})
if not len(id):
return self.write({"success": False})
c.execute(
"DELETE FROM cars WHERE id=?",(carId))
self.write({"success": 200})
except:
self.write({"success": False})
conn.commit()

# Put route to edit an entity in DB.
def put(self, carId):

try:
data = json.loads(self.request.body)
print(data)
print("Updating Cars table")
id = data["id"]
make = data["make"]
model = data["model"]
if not make or not model or not carId:
return self.write({"success": False})
if not len(make) or not len(model):
return self.write({"success": False})
c.execute(
"UPDATE cars SET make=?, model=? WHERE id=?",(make, model, id))
self.write({"success": 200})
except:
self.write({"success": False})
conn.commit()


def verifyDatabase():
try:
c.execute('SELECT * FROM cars')
print('Table already exists')
except:
print('Creating table \'cars\'')
c.execute('CREATE TABLE cars (\
id integer primary key,\
make text,\
model text)')
print('Successfully created table \'cars\'')
conn.commit()

class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/api/cars/?", CarHandler),
(r"/api/cars/[0-9]/?", CarHandler)
]
tornado.web.Application.__init__(self, handlers)

def main():

# Verify the database exists and has the correct layout
verifyDatabase()

app = Application()
app.listen(80)
IOLoop.instance().start()
conn.close()
if __name__ == '__main__':
main()

最佳答案

您需要在正则表达式中使用捕获组来告诉 Tornado 将哪些部分传递给您的方法。将与 carId 对应的部分括起来:

 (r"/api/cars/([0-9])/?", CarHandler)

请注意,carId 将作为字符串传递,因此您可能需要使用 carId = int(carId) 进行转换。 (此外,除非您的汽车 ID 只能是个位数,否则您可能需要使用 ([0-9]+))

关于python - 如何从Put路由和Delete的url获取ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50051919/

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