Creating a blog using Flask with Blueprint involves breaking down your application into modular components for better organization and scalability. Blueprints allow you to define routes, templates, and static files in separate modules. Below is a basic example of how you can structure a Flask blog application using Blueprints:
Fig: 11. **Create Project Structure:**
```
/blog_app
/templates
base.html
home.html
blog
post.html
/static
__init__.py
main.py
/blog
__init__.py
views.py
```
2. **Setup Flask Application:**
In `__init__.py` of the `blog_app` folder:
```python
from flask import Flask
from blog.main import main_bp
def create_app():
app = Flask(__name__)
app.register_blueprint(main_bp)
return app
```
3. **Create Blueprint for Main Views:**
In `main.py` inside the `blog` folder:
```python
from flask import Blueprint, render_template
main_bp = Blueprint('main', __name__)
@main_bp.route('/')
def home():
return render_template('home.html')
@main_bp.route('/blog/<int:post_id>')
def post(post_id):
# Retrieve post with given post_id
# Render post.html with the post data
return render_template('blog/post.html', post=post)
```
4. **Templates:**
- `base.html` in the `templates` folder: This can be your main layout.
- `home.html` in the `templates` folder: This can be the homepage template.
- `post.html` in the `templates/blog` folder: This can be the template to display individual blog posts.
5. **Static Files:**
You can add CSS, JavaScript, and other static files inside the `static` folder.
6. **Run the Application:**
In `main.py`:
```python
from blog_app import create_app
if __name__ == '__main__':
app = create_app()
app.run(debug=True)
```
With this structure, you have a Flask blog application with a modular setup using Blueprints. You can expand this further by adding features like user authentication, comments, etc., by creating more Blueprints and organizing your code accordingly.
0 Comments