Better inputs, better code, better apps

I found a really great repo this week, so I’ll dispense with the intro patter. It’s called webargs and it was written by Steven Loria.

webargs is kind of a Goldilocks library for handling input to your Python app. It’s not too hot (JSON input/output with custom validation code). Not too cold (basic url params via request.args.get('key')). Rather, it’s just right, offering a powerful combination of features and flexibility:

  1. You can feed it URL params, form data, JSON, headers, cookies, or files.
  2. It works with Flask, Django, Bottle, Tornado, Pyramid, or on it’s own.
  3. It supports validation, post processing, required inputs, default values, repeated params, error handling, and more.

So, what can you actually build with it? How about an app that accepts JSON from your internal API, but can also seamlessly handle URL param inputs from a third party widget:

python @app.route('/go') @use_args(user_args, locations=('json', 'query')) # technically, the locations array is unnecessary since webargs will automatically search the input query string, form data, and JSON. def go(args): # app logic

You could also use it to create a webhook, triggered whenever you push to GitHub:

```python from flask import Flask from webargs import Arg from webargs.flaskparser import use_args

Oh look, I can even define nested arguments to match the structure of the JSON payload from GitHub!

hookArgs = { ‘sender’: Arg({ ‘login’: Arg(str, required=True) }), ‘repository’ : Arg({ ‘name’: Arg(str), ‘updated_at’: Arg(str) }) }

app = Flask(name)

@app.route(‘/push’, methods=[‘post’]) @use_args(hookArgs) def push(args): print ‘Welp, ‘+ args[‘sender’][‘login’] +’ just pushed to ‘+ args[‘repository’][‘name’] +’ at ‘+ args[‘repository’][‘updated_at’]

if name == ‘main’: ```

Of course, you could turn that print statement into a tweet, a log event, or whatever. Here it is in action:

webargs screenshot

webargs is pretty neat, I think you should try it out. I bet you’ll find all sorts of reasons to use it.

Comments :)
2017 Neal Shyam