DEV Community

Cover image for Make your first web app using Python and Flask!
jones268
jones268

Posted on

Make your first web app using Python and Flask!

Flask is a micro web framework for Python that's simple and easy to use.

From getting Flask installed, to understanding the basic concepts behind a Flask app, as well as writing our first "Hello World" app, we'll cover it all. So without further delay, let's jump in!

Before you begin Developing your first web app with Python and Flask requires an understanding of some Basic Python programming concepts like: variables, functions, loops, conditionals, objects, and classes.

It also requires an understanding of how to write code that can run on a web server. But it's easy to put your Python apps online with a few clicks.

Hello world

In a terminal, we use pip to install Flask.

pip install flask
Enter fullscreen mode Exit fullscreen mode

As an example, let's take a look at a very simple Flask app. First of all, let's create a new directory for our app:

$ mkdir flask-app 
$ cd flask-app
Enter fullscreen mode Exit fullscreen mode

In this directory, we're going to start with a "hello world" app

Now let's create a file called hello.py and add the following to it:

# hello.py
from flask import Flask
app = Flask(__name__)
def hello_world():
    return 'Hello World'
Enter fullscreen mode Exit fullscreen mode

We will then create another file called app.py that imports our hello function and maps it to the root of our web app:

# app.py
from flask import Flask
from hello import hello_world
app = Flask(__name__)
app.add_url_rule('/', hello_world)
app.run(host='localhost', port=5000)
Enter fullscreen mode Exit fullscreen mode

Finally, we run the dev server:

python app.py
Enter fullscreen mode Exit fullscreen mode

And now we can go to localhost:5000 and see "Hello World".

Routes

Flask provides routes, which are functions that map a URL to a function call. The default behavior is to call the function view , but you can add your own functions to be called in the following manner:

from flask import url_for 

@app.route('/') 
def index(): 
    return 'This is the index page'
Enter fullscreen mode Exit fullscreen mode

URLs starting with / will be handled by this function; if you route with /admin/ then only URLs starting with /admin/ will be handled by this function (see below).

from flask import url_for 

@app.route('/admin') 
def admin(): 
    return 'This is the admin page'
Enter fullscreen mode Exit fullscreen mode

You can return not only text, but also HTML, Javascript, CSS etc. See this example. You can interact with databases and also use it for APIs

If you are new to Flask, I suggest this course

Top comments (0)