mnowotka
mnowotka

Reputation: 17258

Bottle route to handle POST and GET

In my webapp code I keep having constructs like this:

@app.route('some_method/<data>', method=['GET'], name='some_method')
def view(id):
    data = base64.urlsafe_b64decode(data)

    ...

@app.route('some_method', method=['POST'], name='some_method')
def view():
    data = request.files.values()[0].file.read() if len(request.files) else request.body.read()

    ...

Where ... is the same code for both view functions. This is not very DRY. Is there any established good practice to handle both POST and GET in bottle app efficiently?

Upvotes: 1

Views: 3153

Answers (2)

ahmed
ahmed

Reputation: 5590

My approche would be:

@app.route('some_method', method=['GET', 'POST'], name='some_method')
@app.route('some_method/<id>', method=['GET', 'POST'], name='some_method')
def view(id=None):
    if id and request.method == 'POST':
        data = base64.urlsafe_b64decode(data)
    elif request.method == 'GET':
        data = request.files.values()[0].file.read() if len(request.files) else request.body.read()
    else
        pass # handle this 404 error

    ...

Upvotes: 2

tom stratton
tom stratton

Reputation: 678

Easiest way that comes to mind is to put "…" into it's own method/function and just call it

def process_stuff(data):
   . . .

@app.route('some_method/<data>', method=['GET'], name='some_method')
def view(id):
    data = base64.urlsafe_b64decode(data)
    process_stuff(data)

@app.route('some_method', method=['POST'], name='some_method')
def view():
    data = request.files.values()[0].file.read() if len(request.files) else request.body.read()
    process_stuff(data)

Upvotes: 2

Related Questions