我想知道如何为正在使用的API实现“编辑条目”功能。该API使用Flask和Swagger UI。该功能应在网址entries/<entry_id>
上实现。如果成功实现,我应该能够通过条目ID检索条目,更新其详细信息并使用Swagger UI前端保存。
entry_models.py
from datetime import datetime
class DiaryEntry(object):
"""Model of a single diary entry
title: title of diary entry,
body: body of diary entry
"""
def __init__(self, data):
self.title = data['title']
self.body = data['body']
def getDict(self):
return self.__dict__
entry_views.py
from flask import Flask
from flask_restplus import Api, Resource, Namespace, fields
from flask import request, jsonify
from datetime import datetime
from entry_models import DiaryEntry
app = Flask(__name__)
api = Api(app, version='1.0', title='My Diary', description= 'Online journal
where users can pen down their thoughts and feelings')
# data structure to store entry offers
entries = {}
entry = api.model('entry offer', {
'title': fields.String(description='title of diary entry'),
'body': fields.String(description='body of diary entry')
})
@api.route('/api/v1/entries')
class Entries(Resource):
@api.doc(responses={'message': 'diary entry added successfully.',
201: 'Created', 400: 'BAD FORMAT'})
@api.expect(entry)
def post(self):
"""Create an entry."""
data = request.get_json()
# Check whether there is data
if any(data):
# save entry to data structure
# set id for the entry offer
diary_entry = DiaryEntry(data)
entry_id = len(entries) + 1
entries[(entry_id)] = diary_entry.getDict()
response = {'message': 'diary entry added successfully.',
'entry id': entry_id}
return response, 201
else:
return {'message': 'make sure you provide all required fields.'}, 400
@api.doc('list of entries', responses={200: 'OK'})
def get(self):
"""Fetch all entries."""
return (entries)
@api.route('/api/v1/entries/<string:entry_id>')
class SingleEntry(Resource):
@api.doc('Fetch a single entry',
params={'entry_id': 'Id for a single entry'},
responses={200: 'OK', 404: 'NOT FOUND'})
def get(self, entry_id):
"""Fetch a single entry."""
try:
entry = entries[int(entry_id)]
entry['id'] = int(entry_id)
return jsonify(entry)
except Exception as e:
return {'message': 'entry does not exist'}, 404
def edit(self, entry_id):
''' Modify an entry '''
if __name__=='__main__':
app.run(debug=True)