Thursday, May 26, 2011

Python HTTP Requests for Humans

Ever try to use Python's standard library for doing a POST? Or a GETPUT, or DELETE? What about when you have to deal with HTTP Basic Auth?

In a word, ugh.

Let's face it, this is one part of Python that is really not for human consumption. While there are a million things you can do with things like urlliburllib2socketurlparse, the fact of the matter is that implementing anything beyond urllib.urlopen() is a matter of diving into arcane APIs.

Sure, thanks to works like Doug Hellmann's Python Module of the Week and Michael Foord's documentation of urllib2 the problem isn't unsurmountable. Unfortunately, the eclectic mix of libraries and weird APIs means when you have to revisit your code in a few months your code feels like spaghetti.

Do you doubt me?

# This sample gleefully taken from https://gist.github.com/973705

import urllib2

gh_url = 'https://api.github.com'
gh_user= 'user'
gh_pass = 'pass'

req = urllib2.Request(gh_url)

password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, gh_user, gh_pass)

auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)

urllib2.install_opener(opener)

handler = urllib2.urlopen(req)

print handler.getcode()
print handler.headers.getheader('content-type')

# ------
# 200
# 'application/json'

Really?

This much code to make a simple HTTP GET request with some auth?!?

Really?!?

This is a debugging nightmare! Especially when you have to deal with complex service APIs provided by Paypal, Amazon, Google, Authorize.net, and a million other systems.

I bet I could earn a decent living by charging Pythonistas a buck each time they took the shortcut of doing HTTP actions in the shell via curl or wget.

Anyway, wouldn't it be great if we could just call a single function with the URL and auth data as parameters? And that the same dialogue would exist for GET, POST, PUT, DELETE or whatever? Wouldn't that be just plain wonderful? If only we could have that functionality in Python!!!

Fortunately for us, we do have that functionality courtesy of Kenneth Reitz's Requests library! Our verbose code sample above becomes the wonderfully terse and easy-to-memorize script as shown below:

# This sample joyfully taken from https://gist.github.com/973705

import requests

r = requests.get('https://api.github.com', auth=('user', 'pass'))

print r.status_code
print r.headers['content-type']

# ------
# 200
# 'application/json'

Want to do a post with data? Try this:

# This example cooked up by me!

import requests
post_data = {"amount":10000, "service":"writing blog posts"}

r = requests.post('http://example.com/api', post_data, auth=('user', 'pass'))

print r.status_code
print r.headers['content-type']

# ------
# 200
# 'application/json'

The Requests library is still young, but I've yet to run into any bugs or undocumented edge cases. The documentation is awesome, but you don't really need it at all. The library is intuitive, fun, and and there is clearly one way to do.

Monday, May 23, 2011

I love this girl!

In every person's life there are those incredibly memorable experiences that stick with you forever. The entirety of PyCon 2010 is for me that experience. You see, PyCon 2010 saw me introduced to the lovely, talented, and brilliant Audrey Roy.


Moments after I heard her lovely voice for the first time, we looked into each other's eyes. After that moment, I spent every waking moment of the conference finding excuses to spend time with her. Fortunately for me, most of her tastes for talks and social events matched my own. Within days we were dancing in each other's arms.
2010-02-20 23.21.30

By the end of the PyCon we both knew we had something special. So after the conference we both flew back and forth across the country every two weeks for months to keep seeing each other. My phone bill skyrocketed. I became intimately familiar with Skype. It was crazy and magnificent. Finally, on May 5th of 2010 I moved out West to be with her for good.

Audrey may seem shy at first, but she has a fierce heart (FYI, she played Ice Hockey for years and did the bargaining for my car). She has a degree in Electrical Engineering and Computer Science from MIT. She supports me in everything I want to do. If you enjoy Django Packages and follow Open Comparison, she came up with the idea. We cook and eat healthy, and besides our differences on seafood/mac-and-cheese we are a food match. She loves my family and they adore her. She is a talented visual artist in any medium she attempts. As a developer, she learns unbelievably fast and produces high quality code in languages such as Python, C++, JavaScript, Objective-C, and anything else she touches. She hacks the Linux kernel so she can use her preferred peripherals. Her role in the technical community continually grows, and recently she launched the PyLadies advocacy group.
Airborne girlfriend!

An incredible thing about Audrey is that she makes me a better person. I didn't see this at first, but my good friend and mentor Steve Holden pointed it out. She doesn't just bring me joy, she makes me a more tenacious, honest, and compassionate person.

Life is never perfect, but thanks to Audrey and the Python community that brought us together, life is just plain good.

Thursday, May 19, 2011

A couple great Pycon 2011 Talks

Yes, this should have been posted months ago... Anyway, so many great talks at PyCon 2011, here are two great ones! Being an eternal beginner, I try to hit both entry level and advanced talks.

How to write obfuscated Python
Why waste your time with one decorator when 10 of them attached to a function, each named as descriptively as 'X' or 'G' will make your code delightfully hard to interpret? Also included such goodies as 'object = str' which I borrowed for my own Python Worst Practices. In my opinion, Reverend Johnny Healy gave the funniest and obscure talk of the conference, and yet somehow managed to export some useful knowledge in the process.

The Data Structures of Python
Alex Gaynor gave a great 'beginner' talk here. As he went over the basic types in Python, and while he presented well, I wondered if this talk was for me. My hubris was that I thought the talk was beneath me. Then Alex dove into some more sophisticated material like namedtuples and collections and yet again I was reminded how periodically going over the 'basics' is a good thing. Alex kept his talk to a reasonable pace, giving enough time for people to take notes and truly understand what he was teaching. If the whole crazy programming thing doesn't work out for him, he might want to consider becoming an educator.

Monday, April 25, 2011

We won first place at Startup Camp LA!

On a whim we (me and audreyr) decided to try out Startup Camp LA organized by Semantic Seed. This is one of those Silicon Vally style competitions to launch a minimally viable product along with a business plan and marketing pitch in the course of a weekend. We thought it would be a good excuse to hack on a project we've been cooking up in our heads over a year. So we booked our tickets via meetup.com and showed up at the new Nextspace Los Angeles location.

The organizers did a really good great job providing space, food, and lots of useful advice. I look forward to the next event that they run in the area.

Startup Camp LA Pitches

The first pitch was on Confidox, an exclusive recruiting site for lawyers with a focus on clean design, security, and good use of email/sms. The presenter, a professional attorney with great oratory skills, had mockups and a business plan ready to go.

Audrey gave our pitch, which is a site for recruiting developers that is created and maintained by developers. Developers are treated with dignity and respect, and not as replaceable components. We've talked to people on-and-off about this for over a year, and thought this would be a good opportunity to get things moving.

After Confidox and our proposal came a lot of other dreamers.

Then began the bargaining and voting for team placements. Voting was done with paper money. We received the second-highest amount of paper money and Confidox got third place.

Switching projects

As said, our recruiting idea got second place in votes. We got assigned two other people, one of them being the Confidox guy. This meant we got the most paper money total!

Rather than work on our project and have to educate the new guys on the developer ecosystem, we decided to switch to Confidox for the weekend. The scope was reasonable, the plan sound, and the mockups meant we had a specification to code against.

Development

"Ideas are cheap, implementation is hard."

From the start Audrey and I decided to not allow any scope creep. No social media widgets, banner advertisements, forums, branding, coupons, or anything that distracted from the business model. That would allow for a clean design and elegant implementation. We went to work, taking breaks to help hammer out the marketing pitch and socialize with the other teams. Our goal was a stable, functional prototype - something we achieved thanks to our mostly open source technology stack.

Technology Stack

Unless specified otherwise, everything is open source:
The Final Pitches

The Confidox pitch:
  • Our group presented as a team. Marketing talked marketing, techs talked tech.
  • A live prototype site with fully functioning authentication, registration, profiles, listings, search, and email/SMS notifications. 
The other teams presented well, but I was shocked by a few things:
  • Most pitches lacked even a buggy prototype.
  • Presenting teams bickering during their presentations.
  • Unbelievably, one slide presentation had music that the presenter had to shout over.
Why Confidox won Startup Camp LA

Audrey took charge of the group and kept us focused on the elegant, straightforward idea. She didn't just code, she also treated the business side as being equally important as the technical delivery (giving them constant feedback and coaching). Which meant we could both roll out a working prototype and nail the marketing pitch.

When it came down to it, we were a team. Everyone had purpose and everyone contributed. We communicated our idea and demonstrated that our prototype works.

Going forward

Confidox is not off the ground yet, we'll see where it goes. We certainly have a capable team.

This event was a success for us and our company Cartwheel. Also, with ancillary projects with large contributor basis such as Django PackagesPackaginator, and Django Uni-Form, me and Audrey have proven ourselves capable of just launching dynamic projects quickly that work and are used by real people for real work. We'll see what we can do with that proof.

Finally, if you want to learn our techniques for constructing Confidox and other efforts, come to our Los Angeles area classes.

Friday, April 22, 2011

I teach Python and Django

This is one of those blog posts where a developer announces that he/she is teaching for a whole week. The difference is that in this post I'm going to explain why I want to teach and why you should take my classes or send your staff.

I'm an experienced instructor.
I've taught a variety of things for over 20 years, including in alphabetical order: Best practices, Django, English, JQuery, martial arts, Pinax, Python, Selenium, soccer, and unit testing. I speak clearly, get across technical points well, and love the material. I also know how to provide an early foundation of knowledge and then expand upon it for maximum benefit.

I don't just dump knowledge into the heads of my students; I take the time to teach them common standards and best practices, so their code is extendable and maintainable.

I'm not alone. 
Audrey Roy, co-founder of Cartwheel, leader of PyLadies and Django Packages, who has tutored and lab assisted at MIT will be teaching with me, meaning the teacher-to-student ratio is kept at 5:1 for our first offering. 

I want you to surpass me.
After teaching various things for many years I've found it a point of honor and immense pride when a student shines better than myself. I'm not one of those teachers who holds something back so I can always have the edge. In fact, my ultimate goal is to make you better than me.

I rest on the shoulders of giants.
I'm sure the people I'm mentioning in this section are going to roll their eyes, but lets face it - they rock!

In any case, I've had the fortune of helping Steve Holden write Python 3 classes for the O'Reilly School of Technology. I've been exposed to the Django code bases of NASARevSys and Eldarion. While I can't share that work directly, I can take the abstract of their methods and turn it into lessons.

For the employers: Classes are a good way to find resources
Having trouble finding staff? Imagine instead you hire a talented developer from another language and send them to my classes. In a week's time for a fraction of the price they'll have been kickstarted into not just knowing how to do their job, but how to expand their knowledge so if they don't know something, they know who to ask.

Refresher courses are free for six months
Space-permitting, you can retake a class at no charge.

The course schedule
Our first classes are scheduled for May 16th to May 20th. We are offering:
One more thing, if you take both classes we'll give you a 10% discount after registration.

Sunday, April 17, 2011

How NOT to interview Pythonistas

There are a lot of firms who complain that all the experienced Python people are taken, and wonder if they should choose a different toolset. On the flip side of the coin, I've heard a growing  number of developers/engineers complain about horrible hiring practices they encounter. So which is it?

I think it is a mix of both. Compared to the current need, there is a shortage of experienced Pythonistas. On the other hand, I've seen really stupid mistakes by otherwise professional firms, stupid mistakes which are NOT caused by recruiters and don't just cost the firm a possible hire, but hurts their reputation. This is because people will complain to each other on IRC and in users groups about how your firm hires people and all of a sudden your firm has a bad reputation.

So that this stops happening, here are three really bad moves I've seen by companies:

1. If cold calling, don't EVER ask technical questions.

Recently I keep hearing about this one and it even happened to me about 8 years ago.

A pythonista is doing something, maybe coding, driving, sleeping, or eating when they get a call. The pythonista answers and are asked if they are interested in working for Company X. The pythonista gives a positive answer. Then the interviewer asks if they could answer some technical questions.

At this point the interviewer has failed. In fact, they have failed hard.

Odds are that being on the spot, the Pythonista will agree. And then, without a day to prep themselves for doing an interview, they are answering questions. There are no metrics for this one but I bet 90% of developers will fail questions they normally could answer in a heartbeat. Afterwards, the developer/engineer will kick themselves because they knew the answer, but because they were flustered they got things wrong.

And then, to really seal the deal, because the developer/engineer has failed the interview, the interviewer will inform them that they are not the sort of material that Company X wants. So not only did the pythonista mess up easy questions, now the lack of respect for their skills and person has been made abundantly clear.

The interviewer is completely at fault here.

The real problem for the interviewer is that if that potential hire that they just rejected talks about it, experienced developers/engineers will hear about it and it will be a unspoken black mark against their firm.

Lesson learned: What the interviewer should have done is email first, or if they called, ask if they could schedule a technical interview, either in person or on the phone. There is no exception to this system.

2. Make it clear that an interview is an interview.

Imagine there is a company you respect and admire. You meet the founders or the senior technical lead at a social event and they invite you to visit their firm. You arrive at the office expecting a tour and instead get handed to the technical staff for a challenging interview. Unprepared you don't do so well, and unsurprisingly the company doesn't hire you.

This is so full of wrong on the part of the hiring firm I don't know where to begin.

Lesson learned: If you are bringing someone into the office for an interview, make it abundantly clear you are interviewing the prospect. Say it in person and confirm it in email.

3. Make crazy requests in the technical interview

A few years ago a very capable friend was asked to provide a list of Fibonacci numbers, but he wasn't allowed to use a function and need to use a database. When he solved that one his effort was then criticized for 15 minutes by four developers. Then he was then asked to do it again, only this time in ECMA script.

Well before node.js existed, someone else I know was asked to use browser JavaScript to write a multithreaded HTTP server. When my friend asked "why would you ever do such a thing?", he was told not to ask that question but to solve the issued problem.

In all these cases the interviewee left annoyed, if not angry. Years have gone by and they still complain about these firms.

Lesson learned: For the hard questions, make them meaningful

Saturday, April 9, 2011

Are you looking for Python and Django Work?

I've done some consulting work for a company in New York City that is looking for full time developers of all levels. They've got a solid business model, experienced and excellent leadership, and an existing team of talented developers who do things the right way. The founders and developers have been behind a bunch of things you know and love. The company is stable, well-financed, and offers full benefits.

In short: they're building the dream team. They don't use dumb words like rockstar and ninja: they're looking for quietly competent developers with a taste for travel.

Additional experience with CSS, JavaScript/JQuery, GIS, Git, Linux, and experience with contributing to open source projects are definite pluses.

Before you apply you need to pass this little test of mine. If you fail any portion of of this test then we won't consider hiring you.
  • Can you get to the office or are you willing to move closer? When you begin, you need to be able to get to New York City, New York every day of the week. Over time you can work out telecommuting options. 
  • Are you a solitary developer? I'll throw away any responses from recruiters and consulting firms.
  • Bonus Question: Not a requirement but do you have any open source contributions from any languages to share?
  • Can you send your resume to my email address 'hidden' in the code below? To do that, you'll need to know enough about Python to run this code:
    numbers = [83, 101, 110, 100, 32, 114, 101, 115, 117, 109, 101, 32, 116, 111, 32, 112, 121, 100, 97, 110, 110, 121, 64, 112, 121, 100, 97, 110, 110, 121, 46, 99, 111, 109, 32, 119, 105, 116, 104, 32, 115, 117, 98, 106, 101, 99, 116, 32, 111, 102, 32, 39, 108, 111, 102, 116, 121, 39]

    ''.join([chr(x) for x in numbers])