Build Your First Flask Web App: A Quick‑Start Tutorial
This article introduces Flask, a Python micro‑framework, covering installation, a minimal "Hello Flask" example, debugging, routing, URL building, request handling, templates, static files, cookies, sessions, and response customization, providing ready‑to‑run code snippets for each feature.
Installation
Install Flask using pip:
pip install flaskQuick Start
Create a Python file with the following code and run it. Access http://localhost:5000 to see Hello Flask! in the browser.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello Flask!'
if __name__ == '__main__':
app.run()Debug Mode
Enable automatic reloading and debugger output by setting the FLASK_DEBUG environment variable to 1. When the server restarts, you will see messages such as:
* Restarting with stat
* Debugger is active!
* Debugger PIN: 157-063-180
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)Routing
Define routes with the @app.route decorator, similar to Java annotations:
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World'Path Variables
Capture parts of the URL using converters ( string, int, float, path, any, uuid):
@app.route('/user/<username>')
def show_user_profile(username):
return 'User %s' % username
@app.route('/post/<int:post_id>')
def show_post(post_id):
return 'Post %d' % post_idURL Building
Generate URLs with url_for:
from flask import Flask, url_for
app = Flask(__name__)
@app.route('/')
def index():
pass
@app.route('/login')
def login():
pass
@app.route('/user/<username>')
def profile(username):
pass
with app.test_request_context():
print(url_for('index')) # /
print(url_for('login')) # /login
print(url_for('login', next='/')) # /login?next=/
print(url_for('profile', username='John Doe')) # /user/John%20DoeHTTP Methods
Specify allowed methods in the route decorator:
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
# process login
pass
else:
# show login form
passStatic Files
Reference static assets with url_for('static', filename='...'):
url_for('static', filename='style.css')Template Rendering
Flask uses Jinja2 for templates. Render a template with render_template and place HTML files in a templates directory:
from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)Example hello.html:
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
<h1>Hello {{ name }}!</h1>
{% else %}
<h1>Hello, World!</h1>
{% endif %}Logging
Flask provides a pre‑configured logger that behaves like the standard Python logger:
app.logger.debug('A value for debugging')
app.logger.warning('A warning occurred (%d apples)', 42)
app.logger.error('An error occurred')Request Handling
Access request data via the global request object, which is a context‑local proxy.
Request Object
Retrieve form data, query parameters, and files:
from flask import request
@app.route('/login', methods=['POST', 'GET'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
# validate and log in
else:
# show login form
pass
# get query parameter
searchword = request.args.get('key', '')
return render_template('login.html')
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/' + secure_filename(f.filename))
return 'Upload page'Cookies
Read and set cookies:
from flask import request, make_response
@app.route('/')
def index():
username = request.cookies.get('username')
# ...
resp = make_response(render_template('index.html'))
resp.set_cookie('username', 'the username')
return respRedirects and Errors
Use redirect and abort for redirects and error responses, and customize error pages with @app.errorhandler:
from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return respSessions
Manage user sessions with the session object, which stores data in signed cookies:
from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
@app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''<form method="post"><p><input type=text name=username><p><input type=submit value=Login></form>'''
@app.route('/logout')
def logout():
session.pop('username', None)
return redirect(url_for('index'))Template Basics
Jinja2 templates use {% %} for statements and {{ }} for expressions. Templates can extend a base layout, define blocks, and include control flow such as if and for loops.
Inheritance
A child template can inherit from layout.html and override title and body blocks.
Control Flow
Conditional rendering and loops are written directly in the template:
{% if not session.logged_in %}
<a href="{{ url_for('login') }}">log in</a>
{% else %}
<a href="{{ url_for('logout') }}">log out</a>
{% endif %}
{% for key, value in data.items() %}
<tr><td>{{ key }}</td><td>{{ value }}</td></tr>
{% endfor %}Conclusion
The article provides a concise overview of Flask's core features, enabling readers to set up a simple web service, handle requests, manage sessions, and render dynamic pages. For deeper exploration, consult the official Flask documentation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
