[Flask] Ajax(2)

최더디·2020년 9월 2일
0

Flask Ajax

목록 보기
2/2

목표


나는 내가 글을 적고 버튼을 누르면 db에 저장이 되고, 그 값을 html 에 띄우고 싶다.

입력한 데이터 1개만 가져와서 출력하기


"""
index.html
"""
<html>
<head>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <p id="example">AJAX</p>
    <input type="text" id="id1" placeholder="id">
    <input type="text" id="password1" placeholder="password">
    <input type="text" id="email1" placeholder="email">
    <input type="button" id="execute" value="execute">

    
    <div id='div2'>
        
    </div>
    <script>
    `   $('#execute').click(function(){
            var id = $('#id1').val();
            var password = $('#password1').val();
            var email = $('#email1').val();

            var postdata = {
                'id':id, 'password':password, 'email':email
            }
            $.ajax({
                type: 'POST',
                url: '{{url_for("ajax")}}',
                data: JSON.stringify(postdata),
                dataType : 'JSON',
                contentType: "application/json",
                success: function(data){
                    alert('성공! 데이터 값')
                    $('#div2').append('<div>'+ data.result2.id + " " + data.result2.password + " " + data.result2.email  +'</div>')
                },
                error: function(request, status, error){
                    alert('ajax 통신 실패')
                    alert(error);
                }
            })
        })
    </script>
</body>
</html>
"""
__init__.py
"""
import os
from flask import Flask, render_template, url_for, jsonify, request
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate       # DB
import simplejson as json

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'address'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = b'aaa!111/'    # session 사용하려면 필요
db = SQLAlchemy(app)
migrate = Migrate(app, db)

class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.String(30), primary_key=True)
    password = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    pub_time = db.Column(db.DateTime())

    def get_json(self):
        return dict(
            id = self.id,
            password = self.password,
            email = self.email,
            pub_date = self.pub_time
        )

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/ajax', methods=['GET','POST'])
def ajax():
    if request.method=='GET':
        user = User.query.all()
        return render_template('index.html', users=user)
    
    else:
        data = request.get_json()
        
        user_data = User(id=data['id'], password=data['password'], email=data['email'], pub_time=datetime.now())
        db.session.add(user_data)
        db.session.commit()

        return jsonify(result="success", result2=data)

DB에 있는 모든 데이터들 가져와 출력하기


"""
index.html
"""
<html>
<head>
    <script src="https://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <p id="example">AJAX</p>
    <input type="text" id="id1" placeholder="id">
    <input type="text" id="password1" placeholder="password">
    <input type="text" id="email1" placeholder="email">
    <input type="button" id="execute" value="execute">

    
    <div id='div2'>
        
    </div>
    <script>
        $('#execute').click(function(){
            var id = $('#id1').val();
            var password = $('#password1').val();
            var email = $('#email1').val();

            var postdata = {
                'id':id, 'password':password, 'email':email
            }
            $.ajax({
                type: 'POST',
                url: '{{url_for("ajax")}}',
                data: JSON.stringify(postdata),
                dataType : 'JSON',
                contentType: "application/json",
                success: function(data){
                    alert('성공! 데이터 값')
                    $.each(data.result2, function(key,value){
                        alert(key + " : " + value.id + " " +value.password+ " " + value.email)
                        $('#div2').append('<div>'+ value.id + " " + value.password + " " + value.email  +'</div>')
                    })
                    
                },
                error: function(request, status, error){
                    alert('ajax 통신 실패')
                    alert(error);
                }
            })
        })
    </script>
</body>
</html>
"""
__init.py
"""
import os
from flask import Flask, render_template, url_for, jsonify, request
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate       
import simplejson as json

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'address'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.secret_key = b'aaa!111/'    
db = SQLAlchemy(app)
migrate = Migrate(app, db)

class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.String(30), primary_key=True)
    password = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    pub_time = db.Column(db.DateTime())

    def get_json(self):
        return dict(
            id = self.id,
            password = self.password,
            email = self.email,
            pub_date = self.pub_time
        )

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/ajax', methods=['GET','POST'])
def ajax():
    if request.method=='GET':
        user = User.query.all()
        return render_template('index.html', users=user)
    
    else:
        data = request.get_json()
        
        user_data = User(id=data['id'], password=data['password'], email=data['email'], pub_time=datetime.now())
        db.session.add(user_data)
        db.session.commit()

        users = User.query.all()
        data_list = []
        for user in users:
            data_list.append(user.get_json())
        
        print(data_list)
        return jsonify(result="success", result2=data_list)

class User 안에 get_json() 이라는 함수를 만들어 return 값을 dictionary 로 준다.

profile
focus on why

0개의 댓글