flask structure
- Create Project Directory:
Create a project directory to contain your Flask application.
Initialize Virtual Environment:
Navigate to the project directory and create a virtual environment using the command:
python -m venv venv
Activate Virtual Environment:
Activate the virtual environment:
- On Windows:
.\venv\Scripts\activate
- On Unix or MacOS:
source venv/bin/activate
- On Windows:
Install Flask:
Install Flask within the virtual environment:
pip install Flask
Create Flask App File:
Create a Python file (e.g.,
app.py
) to define your Flask application.Import Flask:
Import the Flask class from the Flask module:
python from flask import Flask
Create App Instance:
Create an instance of the Flask class:
python app = Flask(__name__)
Define Route and View Function:
Define a route and a corresponding view function using the
@app.route
decorator:python @app.route('/') def hello_world(): return 'Hello, World!'
Run the App:
Add the following code to run the Flask application:
python if __name__ == '__main__': app.run(debug=True)
Run the Application:
- Run the Flask application using the command:
python app.py
- Run the Flask application using the command:
Access the App:
- Open a web browser and navigate to
http://127.0.0.1:5000/
to view your Flask application.
- Open a web browser and navigate to
Optional: Structure Enhancement:
- Organize your project by creating additional directories for static files, templates, and other resources.
Debug Mode (Optional):
- While developing, you can enable the debug mode to automatically reload the server on code changes:
python app.run(debug=True)
- While developing, you can enable the debug mode to automatically reload the server on code changes:
Deactivate Virtual Environment (Optional):
- When done, deactivate the virtual environment:
deactivate
- When done, deactivate the virtual environment: