Hướng dẫn python flask feature flags

Feature flags allow you to configure your app without writing additional code in your codebase. With dynamic configurations, you can easily specify the experience desired for each segment of users without ever deploying new code. Feature flags are the foundation for progressive delivery, making it easier to test in production, release faster, and deploy code more safely. In this step-by-step tutorial, you will build a Python web app with Flask and then implement feature flags. For this example, you will build a menu application that will store the two menus for my restaurant.

Prerequisites for Python, Flask, Feature Flags, etc.

You will need to install the Python extension for this project. From Visual Studio, click on the extensions tab and search for Python. Look for the extension that looks like this:

Hướng dẫn python flask feature flags

Then, from your terminal, install python3.

brew install python3

You should also be using a virtual environment to download all of the Flask extensions you need. In your root folder, enter the following.

python3 -m venv env

Next, we will select our Python interpreter. In VSCode, from the command palette, search for Python: Select Interpreter.

Hướng dẫn python flask feature flags

Select the path that starts with ./env.

Hướng dẫn python flask feature flags

Now, from the Command Palette, search for Terminal: Create New Integrated Terminal.

Hướng dẫn python flask feature flags

This will automatically activate your virtual environment.

Now, install Flask.

pip3 install flask

You will also need a free developer account from Split, so be sure to sign up if you don’t have one yet!

Create Your Flask App

In your root directory, create a file named app.py and import Flask.

from flask import Flask

app = Flask(__name__)

Next, in the app.py file, you need to add a function that returns content in the home URL.

@app.route("/")

def home():

   return "Hello, Flask!"

In your terminal, run python3 -m flask run. Command-click on the URL that is outputted with the local port. 

Hướng dẫn python flask feature flags

Now that we got the app up and running, let’s add some functionality and styles to it. Update your app.py file to also import render_template and return that in a new function called index(). You can remove the old home function. The new index function will return the index.html file with the new template.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")

def index():

   return render_template('index.html')

In your root directory, create a new folder called templates, and in that folder, create a new file called index.html. Here, enter “!+tab” to render a basic HTML template.

I am going to call my restaurant The Queen’s Gambit, so let’s add that in a new Header.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>The Queen's Gambit</title> </head> <body> <h2>The Queen's Gambit </h2> </body> </html>

Code language: Django (django)

Now, we need to build our menus and add them to the home page. In the templates folder, add a new HTML file called lunch_menu.html and one called happy_hour.html. Then add some tables with the menu items you’d like in each corresponding menu.

Let’s add those routes to our app.py file:

from flask import Flask, render_template app = Flask(__name__) @app.route("/") def index(): return render_template('index.html') @app.route("/lunch") def lunch(): return render_template('lunch_menu.html') @app.route("/happyhour") def happyhour(): return render_template('happy_hour_menu.html')

Code language: Ruby (ruby)

Now we can add the corresponding links to our index.html file.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>The Queen's Gambit</title> </head> <body> <h2>The Queen's Gambit </h2> <h2><a href="/lunch">Lunch Menu</a></h2> <h2><a href="/happyhour">Happy Hour Menu</a></h2> </body> </html>

Code language: Django (django)

When you run python3 -m flask run, you should see your menu app:

Hướng dẫn python flask feature flags

Clicking on each link will take you to the corresponding menu. Now let’s add feature flags.

Create a Feature Flag with Split

The first thing we need to do is create a feature flag from the Split UI. Once you log in, click on Create Split.

Hướng dẫn python flask feature flags
Hướng dẫn python flask feature flags

Next, Click on Add Rules. Here, you will define the different treatments of your feature flag. I am going to define treatment on and treatment off. If the treatment is on for the current user, they will have access to the menu app. If the treatment is off, they will not have access.

Hướng dẫn python flask feature flags

Next, we need to target the specific users who should have access to the app, at least initially, me.

Hướng dẫn python flask feature flags

For everyone else who is not in that list, they will get the default treatment of off because the default rule is off.

Hướng dẫn python flask feature flags

Instantiate and Use the Python SDK

In your root folder, import the Python SDK using pip.

pip install splitio_client[cpphash]==8.3.0

Then, in your app.py file, import the following:

from splitio.exceptions import TimeoutException

from splitio import get_factory

Now we will instantiate the SDK and create a new Split client (still in app.py):

factory = get_factory('YOUR_API_KEY')

try:

   factory.block_until_ready(5)  # wait up to 5 seconds

except TimeoutException:

   pass

To find your API key, go to the Syntax tab of your split, and then select Python as the language.

Hướng dẫn python flask feature flags

In our index function, let’s create a Split client and treatment. In the get_treatment call, you will have two parameters: who the current user is and the name of the split. Then, you need to add our if/else statement to differentiate the different views. Since I only added my name to the targeting rules in the Split UI, only I should be able to see the menus. If someone who is not targeted while the flag is off tries to see the app, you need to create an error page. In your templates folder, create a new file called error.html and add an error message.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>Error</h2> </body> </html>

Code language: Django (django)

Now, in our index function, we can add this template.

@app.route("/") def index(): client = factory.client() treatment = client.get_treatment( 'talia.nassi@split.io', 'the_queens_gambit_menu') if treatment == 'on': return render_template('index.html') else: return render_template('error.html')

Code language: Scala (scala)

Here, we are telling Split that I am the current user, and treatment should be on for me. Let’s run the app and see what happens.

Hướng dẫn python flask feature flags

I can see the app!

Now, let’s change the targeted user to someone who should not have access (i.e., anyone else).

@app.route("/") def index(): client = factory.client() treatment = client.get_treatment( 'test@split.io', 'the_queens_gambit_menu') if treatment == 'on': return render_template('index.html') else: return render_template('error.html')

Code language: Scala (scala)
Hướng dẫn python flask feature flags

The test user does not see our app because they are not targeted.

For the full repo and more examples with feature flags, check out our examples repo.

Improve Your Flask Apps with Feature Flags

Now that you have feature flags implemented, the possibilities are endless! You can test your code in production, make sure it works, and then turn on the flag for your end-users. You can also release your app through a canary release, or percentage rollout, where only a small percentage of your user base has access to the app to mitigate risk in case something goes wrong. With feature flags, you have full control over your app, and Split makes it easy to implement! 

Build More Apps with Feature Flags

Feature flags are foundational to engineering. We at Split love building apps in all different languages and frameworks!

  • Build a CRUD App with Spring Boot and React in 20 Minutes
  • Build a CRUD App with Spring Boot and MongoDB
  • How to Branch by Abstraction with Feature Flags

To stay up to date with all of our content, be sure to follow us on Twitter and subscribe to our Youtube Channel!