본문 바로가기
Python

[Python] Getting Started with Flask

by llHoYall 2020. 10. 11.

In this posting, I'll show you to create a simple web server with Flask.

I usually use Flask when I develop a side project.

You can make it that easily and quickly.

Then, Let's start it.

Installation

$ pip install flask

All you need is Flask.

A Minimal Application

Create app.py file.

from flask import Flask

app = Flask("Hello Flask")


@app.route('/')
def home():
    return 'Hello, World!'

Give the name of your app, in my case I gave the "Hello Flask"

And you need to set the route.

As you already know, '/' means the root directory of the web.

If you access the root of the server, It returns you "Hello, World!".

Now, run this application.

$ flask run

Open your web browser and access to the http://127.0.0.1:5000.

You will be able to see the message "Hello, World!"

Run Flask with Different Environment

Different file name or location

If you change the name of the file or location, Flask can't find it.

So, you have to let Flask know it.

The method is creating an environment variable FLASK_APP.

For example, you named the application as home.py and its location is in the src folder and you are currently working on MAC.

$ export FLASK_APP=src/home.py && flask run

But, if you are working on Windows, it is more complicated.

 

I'll give you a very useful tip.

First, install a module.

$ pip install python-dotenv

And create .env file.

FLASK_APP   = src/app.py
FLASK_ENV   = development

Now, you just run Flask.

$ flask run

You don't have to input any more environment variables.

Do you need more variables? Just add it to this file!

As an example, I added the FLASK_ENV variable to set mode.

This is my present for you. lol

Different IP Address and Port

You can also change the IP address and port of the application.

If you run Flask with a host argument, you can set the IP address.

If you run Flask with a port rgument, you can set the port number.

$ flask run --host="0.0.0.0" --port=1234

Routing

Let's add more route path.

@app.route('/about')
def about():
    return 'This is an about page.'

Access http://127.0.0.1:5000/about through a web browser and see the result.

Route with variable

@app.route('/user/<username>')
def user(username):
    return f'Nice to meet you, {username}'
    

@app.route('/post/<int:post_id>')
def post(post_id):
    return f'This is the {post_id}th post.'

It's so easy enough that there is nothing to explain.

Please check this with http://127.0.0.1:5000/user/hoya and http://127.0.0.1:5000/post/7.

However, when you learn new things, please check which part can be modifiable.

 

Flask helps you easily convert the type of the passed arguments.

Type Description
string (Default) Accepts any text without a slash
int Accepts positive integers
float Accepts positive floating point values
path Like string but also accepts slashes
uuid Accepts UUID strings

Route with query string

from flask import Flask, request


@app.route('/search')
def search():
    searching_text = request.args.get('text')
    return f'You searched with text: {searching_text}'

Now, access the http://127.0.0.1:5000/search?text=python.

Next,  change the code and test it!!

Practice makes perfect!!!

Serve Static Web Pages

You can serve your own static web pages.

Create a templates folder and create hello.html file inside the folder.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello Flask</title>
</head>
<body>
    <h1>Welcome to Flask world</h1>
</body>
</html>

Now, add code into the Flask application.

from flask import Flask, render_template


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

If you access to http://127.0.0.1:5000/hello, you can see the web page that we just created.

Specify HTTP Methods

You can specify the HTTP methods in the route.

@app.route("/user/<username>", methods=["GET", "PUT"])
def user(username):
    if request.method == "GET":
        return f"Nice to meet you, {username}"
    elif request.method == "PUT":
        return f"Created user sucessfully"


@app.route("/post/<int:post_id>", methods=["GET", "POST"])
def post(post_id):
    if request.method == "GET":
        return f"This is the {post_id}th post."
    elif request.method == "POST":
        return f"Updated post successfully"

It is easy to use like the above example.

Using Cookie

Flask also helps easily to use cookie.

from flask import Flask, request, make_response, jsonify


@app.route("/cookie/set")
def set_cookie():
    rsp = make_response(jsonify({"id": "hoya", "password": "1234"}), 200)
    rsp.set_cookie("id", "hoya")
    return rsp


@app.route("/cookie/get")
def get_cookie():
    id = request.cookies.get("id")
    return f"Get ID {id} from cookie"

Flask provides make_response() method and jsonify() method.

I made a response of JSON type with these methods.

You can get a JSON request as well with request.get_json() method.

Please test this code.

Redirection

from flask import Flask, redirect


@app.route("/wrong_path")
def wrong_path():
    return redirect("/")

It is also very very easy!

Error Handling

Flask provides abort() method.

from flask import Flask, abort


@app.route("/abort")
def error_abort():
    abort(401)

You can give an error code to abort() function, then Flask will properly return.

 

Moreover, you can return with your own error pages.

Create a not_found.html file into the templates folder.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hello Flask</title>
</head>
<body>
    <h1 style="color: red;">Page Not Found</h1>
</body>
</html>

And, add this code to the application.

@app.errorhandler(404)
def not_found(error):
    return render_template("not_found.html"), 404

If you can test this code, access to the unavailable path like http://127.0.0.1;5000/test.

Flask with React.js

In most of the usage cases, you will use Flask with a front-end framework like React not a static HTML file.

app = Flask(
    __name__, static_folder="./build", static_url_path="/"
)

@app.route("/"):
    return app.send_static_file("index.html")

Like the above example, give a built application to Flask.

Finish

We found out about Flask together.

Flask is based on Python, so you can easily use together with other Python packages like keras, opencv, etc.

I use Flask when I want to create a simple backend server.

I made a Flask and React application with Python serial communication library for helping my colleagues about working from home several months ago.

Enjoy Flask you guys, too.

'Python' 카테고리의 다른 글

[Python] Templates Static Files in Flask  (0) 2020.10.23
[Python] pathlib module (Object-Oriented Filesystem Paths)  (0) 2020.10.13
[Python] Beautiful Soup4 module  (0) 2020.10.09
[Python] requests module  (0) 2020.10.08
[Python] Abstract Class  (0) 2020.09.28

댓글