Alex Stone
Alex Stone

Reputation: 47354

Python, Flask - How to structure a restful web service method to manage uploaded files?

I have the following method that handles uploading files to my web service. Did I write it in a restful way? In particular, I'm interested in the if statements - should each file operation have it's own method or route defined for it? Or is having multiple "if" statements with a method a good way of handling rest operation?

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;

Upvotes: 1

Views: 761

Answers (2)

scottwernervt
scottwernervt

Reputation: 470

It's more of a personal preference on how you want to structure your Flask REST calls. I prefer the style, separate method for each route, presented by Matt Wright at 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

Upvotes: 1

Tamim Shahriar
Tamim Shahriar

Reputation: 739

I don't see anything wrong with it, but if you use flask-restful extension, then the code will be more beautiful. For example :

class  Fileupload(Resource):

    def get(self):
        pass

    def post(self, user_id):
        pass

    def delete(self, user_id, file_id):
        pass

Upvotes: 2

Related Questions