티스토리 뷰

IT/Flask

[Flask] SQLAlchemy

Dragonz 2020. 9. 9. 17:37
반응형

 

Flask 웹어플리케이션에서 원시 SQL 을 이용하여 RUID 작업을 하는 것은 매우 번거롭고 귀찮은 일이다. SQLAlchemy 를 이용하면 이러한 작업들을 보다 쉽게 처리할 수 있다.

 

파일명 : 17_sqlalchemy.py

from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# 데이터베이스 파일의 절대경로 입력
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////home/pi/project/students.sqlite3'
app.config['SECRET_KEY'] = 'random_string'

db = SQLAlchemy(app)

class students(db.Model) :
    id = db.Column('student_id', db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    city = db.Column(db.String(50))
    addr = db.Column(db.String(200))
    pin = db.Column(db.String(10))

    def __init__ (self, name, city, addr, pin) :
        self.name = name
        self.city = city
        self.addr = addr
        self.pin = pin

@app.route('/')
def show_all() :
    return render_template('17_show_all.html', students = students.query.all())

@app.route('/new', methods=['GET','POST'])
def new() :
    if request.method == 'POST' :
        if not request.form['name'] or \
            not request.form['city'] or \
            not request.form['addr'] :
            flash('Please enter all the fields', 'error')
        else :
            student = students(request.form['name'], request.form['city'], request.form['addr'], request.form['pin'])
            db.session.add(student)
            db.session.commit()
            flash('Record was successfully added')
            return redirect(url_for('show_all'))
    return render_template('17_new.html')

if __name__ == '__main__' :
    db.create_all()
    app.run(debug = True)

 

파일명 : 17_show_all.html

<!doctype html>
<html>
    <body>
        <h3><a href = "{{ url_for('show_all') }}">Comments - Flask SQLAlchemy example</a></h3>
        <hr/>
        {% for message in get_flashed_messages() %}
        {{ message }}
        {%- endfor %}

        <h3>Students (<a href = "{{ url_for('new') }}">Add Student</a>)</h3>

        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>City</th>
                    <th>Address</th>
                    <th>Pin</th>
                </tr>
            </thead>
            <tbody>
                {% for student in students %}
                <tr>
                    <td>{{ student.name }}</td>
                    <td>{{ student.city }}</td>
                    <td>{{ student.addr }}</td>
                    <td>{{ student.pin }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </body>
</html>

 

파일명 : 17_new.html

<!doctype html>
<html>
    <body>
        <h3>Students - Flask SQLAlchemy example</h3>
        <hr/>

        {%- for category, message in get_flashed_messages(with_categories = true) %}
        <div class = "alert alert-danger">
            {{ message }}
        </div>
        {%- endfor %}

        <form action = "{{ request.path }}" method = "POST">
            <label for = "name">Name</label><br/>
            <input type = "text" name = "name" placeholder = "name" /><br/>
            <label for = "city">City</label><br/>
            <input type = "text" name = "city" placeholder = "city" /><br/>
            <label for = "addr">Addr</label><br/>
            <textarea name = "addr" placeholder = "addr"></textarea>><br/>
            <label for = "PIN">PIN</label><br/>
            <input type = "text" name = "pin" placeholder = "pin" /><br/>
            <input type = "submit" value = "Submit" />
        </form>
    </body>
</html>

 

Add Student 를 클릭하여 신규 데이터를 INSERT 한다

 

테스트 데이터 입력

 

입력된 데이터가 첫 화면에 정상적으로 출력된다

 

flash 메세지 형태로 정상처리 되었다는 메세지 출력

 

END

반응형

'IT > Flask' 카테고리의 다른 글

[Flask] SQLite3  (0) 2020.09.09
[Flask] WTF (Flask-WTF)  (0) 2020.09.09
[Flask] 메일발송 (Mail)  (0) 2020.09.05
[Flask] 파일 업로딩 (File Uploading)  (0) 2020.08.26
[Flask] 메세지 플래싱 (Message Flashing)  (0) 2020.08.14
댓글
공지사항