Welcome back to CodeYourCraft! Today, we're diving deep into Flask instance folders. If you're new here, Flask is a micro web framework written in Python. Let's get started!
Instance folders are a way to separate application data across multiple instances of your Flask application. They're especially useful in production environments, where you might have multiple instances of your app running simultaneously.
First, let's set up our project structure. Create a new folder and navigate into it:
mkdir my_flask_app
cd my_flask_appNow, let's create our basic Flask app:
pip install flask
touch app.pyOpen app.py and write the following code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)Create a folder named templates inside my_flask_app and create a home.html file inside it:
<h1>Welcome to my Flask app!</h1>Now, let's create an instance folder and set it up:
mkdir instances
touch instances/config.pyOpen config.py and write the following code:
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
SECRET_KEY = 'your_secret_key'
UPLOADED_PATH = os.path.join(basedir, 'instances', 'uploads')Replace 'your_secret_key' with a secret key of your choice.
Now, let's modify our app.py to use the instance folder:
from flask import Flask, render_template
from instances.config import Config
app = Flask(__name__)
app.config.from_object(Config)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)Now, let's create a simple file upload feature. Update your home.html file:
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>Update app.py to handle file uploads:
from flask import Flask, request, redirect, url_for, send_from_directory
from instances.config import Config
app = Flask(__name__)
app.config.from_object(Config)
@app.route('/upload', methods=['POST'])
def upload_file():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file:
file.save(os.path.join(app.config['UPLOADED_PATH'], file.filename))
return send_from_directory(app.config['UPLOADED_PATH'], file.filename)
if __name__ == '__main__':
app.run(debug=True)Now, you can run your app and upload files!
What is the purpose of instance folders in Flask applications?
That's it for today! We've learned about instance folders in Flask and how to set them up in our applications. In the next lesson, we'll dive deeper into file handling in Flask.
Until next time, happy coding! 💻🎓