I am pretty new to python/non-Microsoft stack. In this post, I reflect on building a REST web services with python/Flask.
python
Coming from Microsoft background, I was skeptical about building REST web services with python. I didn't know python at the start of the project and was the main reason for my apprehensions. It turned out, learning python wasn't a big issue. Although, some python qualities/limitations kept the development process pretty interesting/challenging.
In my opinion, python is not suitable for *large codebase* because of the following reasons:
- Python is a scripting language (no compile-time error detection).
- Not a true object oriented language.
- Complete mess upgrading versions (2.x vs 3.x).
On the other hand, python has some cool features (I wish .NET had).
- Virtual environment.
- Testing python code is 100 times easier than testing .NET code.
- Tuples - .NET has them but they are not as hip.
- Deployment with "cp -r"
Flask
There are many frameworks available to build REST web services with python. I settled on Flask because it seemed the most popular one. For some reason, I was expecting an official framework, just like ASP.NET is for .NET.
Flask is light weight and easy to use framework. It comes with an inbuilt web server. It's embarrasing that I was stucked with the inbuilt web server for a long time before realizing that the web server is not suited for production purpose. This situation is not different from ASP.NET/Visual Studio. Although, in case of Viusal Studio the development server is rarely used.
Routing and Resources
Flask's extenstion (Flask-RESTful) comes with base class Resource
. It should be use for web methods exposed on a resource.
This blog post explains how it works.
While it is not required to use Resource
base class, I highly recommend it. If the code doesn't use it, route
maintainence is challenging.
virtualenv
I absolutely love virtaulenv. Super easy way to isolate dependencies. I highly recommend using virtualenv during development/testing. It is also a good practice to have "requirements.txt" and "testrequirements.txt" separately.
No virtualenv please
While virtualenv is great for development, I don't think it should be used for production. There are some known issues with virtaulenv.
Instead of using virtualenv in the production, it would be better to use Docker. Docker gives the necessary isolation and easy to deploy mechanism. python already has containers published on Docker hub.
Nginx
Ditch the inbuild Flask webserver for nginx. This should be a no-brainer for deploying REST web services in production. My previous blog talks about this topic.
Super thanks to Miguel. His blog helped a LOT. There is still so much to learn.