A Flask server provides the essential tools for web development—like routing URLs to your Python code—without forcing a specific structure or including non-essential features.
It has a built-in development server that’s perfect for building and testing your app. For a live website, you’d run your Flask app with a more powerful, WSGI production-ready server.
Key Concepts
Micro Framework: Flask’s core is small and extendable. It handles the basics and lets you choose libraries for other tasks (like database access), giving you maximum flexibility.
WSGI: It’s built on the Web Server Gateway Interface (WSGI), the standard Python interface between web servers and web applications.
Development vs. Production Server: The server started with the flask run command is only for development. It’s not secure or efficient enough to handle real user traffic. Production apps use robust WSGI servers like Gunicorn or uWSGI.
How to Set It Up
Here’s a step-by-step guide to creating a simple “Home page” Flask application.
Set Up the Project and Virtual Environment
First, make sure you have Python installed. It’s a best practice to use a virtual environment to manage project dependencies separately.
Create a project folder and navigate into it
sh
mkdir flask_servercd flask_server
Create a virtual environment
sh
python -m venv venv
Activate the environment:
macOS/Linux: source venv/bin/activate
Windows: .\venv\Scripts\activate
You’ll see (venv) appear in your command prompt.
Install Flask
With the virtual environment active, install Flask using pip.
sh
pip install Flask
Create the Flask Application File
Create a Python file named server.py and add the following code:
Import the Flask class
from flask import Flask
python
# Create an instance of the app# __name__ tells Flask where to find resourcesapp = Flask(__name__)
Use the route() decorator to bind a URL to a function
python
@app.route('/')def index():# The function returns the text to display in the browser return 'Home page'
4. Run the Development Server
In your terminal, run the application using the flask command.sh
flask --app server run
You should see output indicating the server is running:
* Serving Flask app 'app'
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
TIP
You can enable debug mode by run the with --debug parameter
sh
flask --app server run --debug
The final code looks like this in the end
python
from flask import Flaskapp = Flask(__name__)app.route('/')def index(): return 'Home page'
Now, open your web browser and go to http://127.0.0.1:5000. You’ll see your “Home page” message. That’s it! You’ve successfully run a basic Flask server.
Comments
We accept only respectful comments. Any one who abuse this directive will be blocked from sending further comments. Read our comment policies for more information