Python, Flask - 如何构建管理上传文件的RESTful服务方法?
我有一个方法用来处理文件上传到我的网络服务。请问我这样写算不算符合REST风格?特别是,我想知道这些if语句——每个文件操作是否应该有自己单独的方法或路由?还是说用一个方法里面有多个“if”语句来处理REST操作也是可以的?
from flask import Flask
from flask import Response, request, redirect, url_for
@app.route('/files/<type>/<id>', methods=['GET', 'POST', 'DELETE'])
def manage_files(type,id):
if request.method == 'POST':
#add a note
if request.method == 'GET':
#retrieve a note
if request.method == 'DELETE':
#delete a file
return;
2 个回答
1
这其实更多是个人的喜好,关于你想怎么组织你的Flask REST调用。我比较喜欢Matt Wright在http://mattupstate.com/python/2013/06/26/how-i-structure-my-flask-applications.html中介绍的那种风格,也就是每个路由用一个单独的方法来处理。
@app.route('/files/<type>/<id>'):
def show_file(type, id):
return None
@app.route('/files/<type>', methods=['POST']):
def new_file(type):
return None
@app.route('/files/<type>/<id>', methods=['DELETE']):
def delete_file(type, id):
return None
2
我觉得这段代码没什么问题,不过如果你使用flask-restful扩展的话,代码会更好看。比如说:
class Fileupload(Resource):
def get(self):
pass
def post(self, user_id):
pass
def delete(self, user_id, file_id):
pass