Skip to main content

🐍 Flask ve SQLite ile Sıfırdan Web Blog Uygulaması Geliştirme


💡 Bu Rehberde Ne Öğreneceksiniz

Bu rehberde, hafif ve esnek bir Python web çatısı olan Flask ile tam işlevli bir blog uygulaması geliştireceksiniz. Uygulamanızı SQLite veritabanı ile entegre edecek, Bootstrap ile modern bir arayüz oluşturacak ve Jinja template motoru sayesinde dinamik HTML sayfaları hazırlayacaksınız. Ayrıca CRUD (Oluştur, Oku, Güncelle, Sil) işlemlerini adım adım öğreneceksiniz.


⚙️ Gereksinimler

  • Python 3 ve pip kurulu bir sistem
  • Sanal ortam (venv) bilgisi
  • Temel Python bilgisi (for döngüsü, fonksiyonlar, değişkenler)
  • Proje dizini: flask_blog

🔧 1. Adım – Flask Kurulumu ve Sanal Ortam Ayarı

Sanal ortamı başlatın:

python3 -m venv env
source env/bin/activate

Flask’i yükleyin:

pip install flask

Kurulumu test edin:

python -c "import flask; print(flask.__version__)"

Bu komut, Flask’in doğru kurulduğunu doğrular.


🚀 2. Adım – Temel Uygulama (hello.py)

hello.py dosyası oluşturun:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
return 'Merhaba, Dünya!'

Uygulamayı çalıştırın:

export FLASK_APP=hello
export FLASK_ENV=development
flask run

Tarayıcıda http://127.0.0.1:5000’ye gidin → “Merhaba, Dünya!” görüyorsanız her şey tamam.


🧱 3. Adım – HTML Template’leri ve Bootstrap Kullanımı

Flask, Jinja2 şablon motorunu kullanır. Şimdi templates klasörünü oluşturun:

mkdir templates

templates/index.html dosyası:

{% extends 'base.html' %}

{% block content %}
<h1>{% block title %} FlaskBlog’a Hoş Geldiniz {% endblock %}</h1>
{% endblock %}

Ana şablon base.html:

<!doctype html>
<html lang="tr">
<head>
<meta charset="utf-8">
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-light bg-light">
<a class="navbar-brand" href="{{ url_for('index') }}">FlaskBlog</a>
</nav>
<div class="container">
{% block content %}{% endblock %}
</div>
</body>
</html>

Bu yapı, “template inheritance” (şablon kalıtımı) ile tüm sayfalara ortak görünüm sağlar.


🗃️ 4. Adım – SQLite Veritabanı Kurulumu

Veritabanı Şeması (schema.sql)

DROP TABLE IF EXISTS posts;
CREATE TABLE posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
title TEXT NOT NULL,
content TEXT NOT NULL
);

Veritabanını Başlat (init_db.py)

import sqlite3

connection = sqlite3.connect('database.db')
with open('schema.sql') as f:
connection.executescript(f.read())

cur = connection.cursor()
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
('İlk Gönderi', 'Bu, ilk blog gönderisidir.'))
connection.commit()
connection.close()

Çalıştırın:

python init_db.py

database.db oluşturulmuşsa veritabanı hazır.


📄 5. Adım – Tüm Gönderileri Listeleme

app.py dosyasını oluşturun:

import sqlite3
from flask import Flask, render_template

app = Flask(__name__)

def get_db_connection():
conn = sqlite3.connect('database.db')
conn.row_factory = sqlite3.Row
return conn

@app.route('/')
def index():
conn = get_db_connection()
posts = conn.execute('SELECT * FROM posts').fetchall()
conn.close()
return render_template('index.html', posts=posts)

index.html dosyasında gönderileri listeleyin:

{% for post in posts %}
<a href="{{ url_for('post', post_id=post['id']) }}">
<h2>{{ post['title'] }}</h2>
</a>
<small>{{ post['created'] }}</small>
<hr>
{% endfor %}

row_factory ayarı sayesinde sütunlara isimle erişebilirsiniz (örnek: post['title']).


🧠 6. Adım – Tek Gönderiyi Görüntüleme

Yardımcı fonksiyon:

from flask import abort

def get_post(post_id):
conn = get_db_connection()
post = conn.execute('SELECT * FROM posts WHERE id = ?', (post_id,)).fetchone()
conn.close()
if post is None:
abort(404)
return post

Rota:

@app.route('/<int:post_id>')
def post(post_id):
post = get_post(post_id)
return render_template('post.html', post=post)

post.html:

{% extends 'base.html' %}
{% block content %}
<h2>{{ post['title'] }}</h2>
<p>{{ post['content'] }}</p>
<small>{{ post['created'] }}</small>
{% endblock %}

🧩 7. Adım – Yeni Gönderi Ekleme

create.html:

<form method="POST">
<input type="text" name="title" placeholder="Başlık">
<textarea name="content" placeholder="İçerik"></textarea>
<button type="submit">Kaydet</button>
</form>

app.py’de rota:

from flask import request, redirect, url_for

@app.route('/create', methods=('GET', 'POST'))
def create():
if request.method == 'POST':
title = request.form['title']
content = request.form['content']
if title:
conn = get_db_connection()
conn.execute('INSERT INTO posts (title, content) VALUES (?, ?)', (title, content))
conn.commit()
conn.close()
return redirect(url_for('index'))
return render_template('create.html')

⚙️ 8. Adım – Üretim Dağıtımı

Gunicorn ile:

pip install gunicorn
gunicorn app:app --bind 0.0.0.0:8000

Alternatif – Rabisu Cloud’da:

  1. Flask projenizi GitHub’a yükleyin
  2. App Platform panelinden “Yeni Uygulama” oluşturun
  3. gunicorn app:app komutunu çalıştırma ayarına ekleyin
  4. Ortam değişkenlerini (FLASK_APP, FLASK_ENV) ekleyin

❓ Sıkça Sorulan Sorular (SSS)

1. Flask neden mikro framework’tür?

Çünkü yalnızca temel özellikleri (routing, template) sunar; diğer bileşenleri isteğe bağlı ekleyebilirsiniz.

2. SQLite yerine başka DB kullanabilir miyim?

Evet, PostgreSQL veya MySQL gibi sistemlerle uyumludur. Yalnızca bağlantı sürücüsünü değiştirmeniz yeterli.

3. Flask geliştirme sunucusu neden üretimde kullanılmaz?

Güvenlik ve performans eksikleri nedeniyle. Üretimde Gunicorn veya uWSGI önerilir.

4. url_for() fonksiyonunun avantajı nedir?

Rota isimlerine göre URL oluşturur. Rota değişse bile linkler bozulmaz — bu SEO ve UX için çok avantajlıdır.

5. Hataları nasıl yönetebilirim?

abort(404) veya özel hata sayfaları (errorhandler) kullanabilirsiniz.


🏁 Sonuç

Tebrikler 🎉 Artık Flask ve SQLite kullanarak tam işlevli bir web blog uygulaması geliştirdiniz. Routing, template kalıtımı, veritabanı işlemleri ve CRUD mantığını öğrendiniz.

🚀 Daha ileri konular: kullanıcı girişi, kimlik doğrulama, API entegrasyonu, resim yükleme.

💡 Projenizi Rabisu Bulut Sunucularında birkaç dakika içinde barındırabilirsiniz. Rabisu ile Python + Flask ortamını kolayca dağıtın!