我用Flask创建了一个CRUD端点,但是当我尝试获取数据时,收到404错误。我尝试使用' http://127.0.0.1:5002/albums/beck//'来访问此终结点。和' http://127.0.0.1:5002/albums/beck'但仍然得到404.因为我提供了贝克'作为艺术家的名字,我认为get方法运行良好。我想我添加的资源不正确。
class Artistdetails(Resource):
def get(self, artist_name):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_name = artist_name.replace(char, "")
query_db = conn.execute("SELECT DISTINCT album FROM album WHERE artist='{0}'".format(artist_name.title()))
result = jsonify({'artistAlbumList': [i[0] for i in query_db.cursor.fetchall()]})
return result
def put(self, artist_name, album_name, album_name_new):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_name = artist_name.replace(char, "")
query_db = conn.execute("UPDATE album SET album='{0}' WHERE artist='{1}' AND"
" album='{2}'".format(artist_name.title(), album_name.title(), album_name_new.title()))
result = jsonify({'putAlbumId': [i[0] for i in query_db.cursor.fetchall()]})
return result, 201
def post(self, artist_name, album_name):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_name = artist_name.replace(char, "")
query_db = conn.execute("INSERT INTO album (album, artist) VALUES"
" ({0},{1})".format(artist_name.title(), album_name.title()))
result = jsonify({'postAlbumId': [i[0] for i in query_db.cursor.fetchall()]})
return result, 201
def delete(self, artist_name, album_name):
conn = db_connect.connect()
# Protect against SQL injection
restricted_char = "!=<>*0&|/\\"
for char in restricted_char:
artist_id = artist_name.replace(char, "")
album_id = album_name.replace(char, "")
query_db = conn.execute("DELETE FROM album WHERE"
" artist_id='{0}' AND album_id='{1}'".format(artist_name, album_name)
)
result = jsonify({'deleteAlbumId': [i[0] for i in query_db.cursor.fetchall()]})
return result, 204
api.add_resource(Api, '/')
api.add_resource(Albums, '/albums')
api.add_resource(Artistdetails, '/albums/<string:artist_name>/<string:album_name>/<string:album_name_new>')
api.add_resource(Genreyear, '/albums/yr')
api.add_resource(Genrenum, '/albums/genre')
api.add_resource(Artists, '/artists')
答案 0 :(得分:1)
这一行:
api.add_resource(Artistdetails,
'/albums/<string:artist_name>/<string:album_name>/<string:album_name_new>')
它添加了Flask路由器的路径,使其期望/albums/<artist_name>/<album_name>/<album_name_new>
,而您尝试请求/albums/<artist_name>
,这与任何内容都不匹配。
快速解决问题的方法是:
api.add_resource(Artistdetails, '/albums/<string:artist_name>')
但是,您可能希望支持搜索界面的查询字符串参数,以便请求看起来更像这样:
/albums?artist=<string>&album_name=<string>