首页 新闻 赞助 找找看

flask_restful 一个Resource有办法实现django的ModelViewSet的效果吗

0
悬赏园豆:5 [待解决问题]

/good
get获取列表,post新增一条数据,其他方法put,delete直接返回404
/good/1
get获取一条,put修改一条,delete删除一条,post返回404
目前是这样写,是否每个方法都要写个article_id=None的默认参数,再在方法体里加判断是否为None,我是刚转的flask,请问是否有比较正规的写法吗

@api.route('/article/<article_id>', '/article')
class ArticleResource(Resource):
    """查询修改删除单条"""
    def get(self, article_id=None):
        if article_id is not None:
            print(article_id)
            article = Article.query.get_or_404(article_id)
            return marshal(article, article_fields)
        else:
            page = int(request.args.get('page', 1))
            pagination = Article.query.paginate(page=page, per_page=3)
            data = {'count': pagination.total, 'next': pagination.next_num,
                    'previous': pagination.prev_num,
                    'results': pagination.items}
            return marshal(data, article_list_fields)

    @login_required
    def post(self, article_id=None):
        if article_id is not None:
            abort(404)

    def put(self, article_id=None):
        if article_id is None:
            abort(404)

不识少年愁的主页 不识少年愁 | 初学一级 | 园豆:62
提问于:2022-01-11 11:08
< >
分享
所有回答(2)
0

可以封装一下啊

小码果 | 园豆:202 (菜鸟二级) | 2022-01-11 11:11

不好意思我是刚转的flask,请问有比较正规的写法吗

支持(0) 反对(0) 不识少年愁 | 园豆:62 (初学一级) | 2022-01-11 11:26
0

我目前用的两种

# 第一种
// file:book.py
@api.route('/<int:isbn>/detail')
def detail(isbn):
    book = Book.query.filter_by(cid=isbn).first_or_404()
    return jsonify(book)


# 第二种
// urls.py
home_api.add_url_rule('/index', view_func=home_index)   # 路由 test  #
home_api.add_url_rule('/func', view_func=TestView.as_view('login'))

// file: views.py
# @home_api.route('', methods=['GET'])
def home_index():
    return "home index"
class TestView(MethodView):

    @query(PageLimitSchema())
    def get(self, query_parsed):
        return query_parsed

    @use_args(FuncTestSchema())
    def post(self, args):
        # return jsonify(args)
        return "TestView post"

按你标题的意思,可能是第二种吧;但常用的基本是第一种,像Blueprint、Flask 都可以去改造,如果前期不会就去找开源的项目 copy (项目结构)

〆灬丶 | 园豆:2287 (老鸟四级) | 2022-01-11 14:48
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册