Building your first web app using Python/Flask
In this post we will see how to quickly set up flask for web development and build a small basic website. You can extend the idea after that - I'll provide resources as well.
Setup directory and libraries
$ mkdir website
$ cd website
$ virtualenv venv
If you don't have virtualenv installed, install it using
$ pip install virtualenv
$ source venv/bin/activate
After this, your prompt changes to :
Let's install Flask library into this virtual environment
$ pip install flask
We're set up, let's jump into some code. Create a new file by any name, let's say:
main.py. So, just do
touch main.py to create it.
We also need a html file, so also create an
from flask import Flask, render_template app = Flask(__name__) def main(): return render_template('index.html') if __name__ == '__main__': app.run(debug=True)
<html> <head> <title>My Homepage</title> </head> <body> Welcome to my website. This is running on a Python server handled by Flask micro web framework. </body> </html>
To start the server:
$ python main.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger pin code: 742-112-915
and you can visit your website locally at :
http://127.0.0.1:5000 or simply
Simple. Isn't it ?
Now, I haven't written anything fancy inside the html file, but you can extend it as much as you want.
Also, in the
main.py file, there is only one route for landing on the root page of the website. If you want to have another effect on some other route like
/contact, you can write a new route with a new function returning the specific html page. (Don't worry, if you don't know what a route is for now).
Now that you have learnt (or just saw) how easy it is with Python + Flask to build simple website/webapp, why don't you try to go and learn more about it ?
- Flask Official Documentation
- Flask tutorial by Miguel Grinberg Go through all 18 parts - you'll be sorted for life
Questions / Want to learn more Hit me up ?
Book a session with me