Codementor Events

Building your first web app using Python/Flask

Published Feb 10, 2017Last updated Aug 17, 2018
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 : $ (venv)

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.


main.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

We also need a html file, so also create an index.html file. Apparently in Flask, to render the HTML pages, we have to use a templates folder. Let's create a templates folder, and create a new HTML file index.html


templates/index.html

<!DOCTYPE html>
<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 http://localhost:5000

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 /about or /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 ?

Resources

Questions / Want to learn more Hit me up ?
Book a session with me

Discover and read more posts from Manoj Pandey
get started
post comments2Replies
Kris Weber
7 years ago

By far the best tutorial I’ve come across for making your first flask app. Thanks! Just one note – you should mention that you need to put your index.html file in the templates folder.

abhishek agrahari
7 years ago

correct. Today I tied the default example as it is and noticed that the example was not working. Once i create a directory template and kept the index.html file inside the “template” folder, it worked very well…
If possible please update the above mentioned process step.