Let’s say you’ve built an interesting Python application that runs locally on your machine. Great! Now how can you make that application usable as a service or an API? A lot of times, people build many services that need to play well together to build a final application. An obvious solution to this is to build a web server like Django that can host your application and handle all the incoming requests. But building a full fledged web server seems like an overkill, especially when you are dealing with lightweight services that only need a couple of functionalities. This is where Flask comes into picture! Flask is a Python microframework that can be used to build web servers and create web applications. How do we do that? How do we build a server that can handle different types of requests?
One of the best things about Flask is that it’s really simple to set up and very easy to use. This is in contrast with Django where there’s a learning curve involved. If you are a developer who just needs to API-fy your application, Flask is the answer! It doesn’t come with all the bells and whistles of Django, but it solves a wide variety of problems by addressing everyday use-cases.
Before you start, make sure you have pip installed. If you are on Mac OS X, then install Python using Homebrew. That would automatically install pip for you! If you haven’t installed Python using Homebrew, you should definitely give it a try. It will save from a lot of headache everywhere in Python-land! If you are on Ubuntu, just run the following command on your terminal:
$ sudo apt-get install python-pip
We are now ready to install Flask. Run the following command on your terminal:
$ pip install flask
You should see the installation success message printed on your terminal.
How to use it?
Let’s create a simple app to understand how Flask works. Create a new python file called “myflaskapp.py” and add the following lines:
from flask import Flask app = Flask(__name__) @app.route('/') def display(): return "Looks like it works!" if __name__=='__main__': app.run()
Save the file and run the following command on your terminal:
$ python myflaskapp.py
Open up your favorite browser and go to http://localhost:5000 and you will see “Looks like it works!” printed there. You just hosted a simple web server on your machine that serves static text!
When you are using Flask, it is generally a good practice to run the app in the debug mode. You can also control the port number. Make the following changes in your python file:
Now run the code and go to http://localhost:3134 to see the output. If you want to make this application accessible externally using the IP address, then you need to tell Flask by specifying the host parameter. Make the following change in your python file:
app.run(host='0.0.0.0', debug=True, port=3134)
Run the code and go to http://x.x.x.x:3134 (replace x.x.x.x with the right IP address) to see your external web server live!
How to specify paths in the URL?
Let’s say you want your server to perform different things based on the path specified in the address bar. For example, if the address is http://localhost:5000/alpha, we want to print “This is the alpha version” and if the address is http://localhost:5000/beta, we want to print “This is the beta version”. To do that, create a new python file and add the following lines:
from flask import Flask app = Flask(__name__) @app.route('/alpha') def alpha(): return "This is the alpha version" @app.route('/beta') def beta(): return "This is the beta version" if __name__=='__main__': app.run(debug=True)
Run the code and check out the URL paths to see the right text printed on your browser.
Can we display HTML pages?
Yes, we can! Create a folder called “templates” and then create a file called “myfile.html” inside that folder. It is important to maintain this folder structure because Flask looks for HTML files in a folder called “templates” located in the current folder. Add the following lines to that HTML file:
<!DOCTYPE html> <html lang="en"> <head> <title>My title</title> </head> <body> <p>Flask can display HTML pages</p> </body> </html>
Now create a new python file and add the following lines:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def render(): return render_template('myfile.html') if __name__=='__main__': app.run(debug=True)
Now run the python code from the terminal and go to http://localhost:5000 to see your HTML page being rendered.
How to grab the URL parameters?
When you are designing an API, you would want to access the input params from the address bar. For example, it can be the username, filename, or some flag specifying an action. Create a new python file and add the following lines:
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/input') def render(): if 'filename' in request.args: myfilename = request.args.get('filename') return render_template(myfilename) else: return "No input file specified" if __name__=='__main__': app.run(debug=True)
We changed our application so that we can specify the HTML file in the URL as opposed to hard-coding it in the python file. Run the code and go to “http://localhost:5000/input?filename=myfile.html” on your browser. You will see the HTML file rendered just like before. We have added an if-else condition in the code that takes care of the case where you don’t specify the file. In that case, it will display an appropriate error message. If you go to http://localhost:5000/input, you will see the message “No input file specified”.