Building a Simple Web Application with Python Flask
This tutorial guides readers through setting up a Python environment, installing Flask, creating a basic Flask app with routes, running the server, accessing it via a browser, and extending the application with form handling and MySQL database integration, all illustrated with clear code examples.
Python Flask is a lightweight web framework that is simple, flexible, and suitable for building web applications of various scales.
Part 1: Set up the development environment
Ensure Python and pip are installed, then run the following command to install Flask:
pip install flask
Part 2: Create the Flask application
Create a file named app.py and add the following code to import Flask and create an app instance:
from flask import Flask
app = Flask(__name__)
Define a route and view function that returns a simple string:
@app.route('/')
def index():
return 'Hello, Flask!'
Part 3: Run the Flask application
Add the entry point at the end of app.py :
if __name__ == '__main__':
app.run()
Start the server from the command line:
python app.py
The console will display a message such as Running on http://127.0.0.1:5000/ , indicating the app is listening on port 5000.
Part 4: Access the application
Open a web browser and navigate to http://127.0.0.1:5000/ ; you should see the text "Hello, Flask!".
Part 5: Add more features – Form handling
Flask can process user‑submitted forms. Create an HTML <form> with method="POST" and action="/login" , then define a /login route that uses request.form.get() to retrieve and validate the submitted data.
Part 6: Database integration
To integrate MySQL, import the MySQL driver, configure the connection, and create a helper function such as get_db_connection() . Use the connection inside view functions to execute queries and return results, then run the app as before.
Remember to adjust the database connection parameters (host, user, password, database) and install the required driver (e.g., mysql-connector-python ).
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
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.