설치
!pip install flask_sqlalchemy
!pip install cx_Oracle
예제
%%writefile crud.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask import request
from flask import jsonify
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
oracle ='oracle+cx_oracle://scott:TIGER@localhost:1521/?service_name=XE'
app.config['SQLALCHEMY_DATABASE_URI'] = oracle
db = SQLAlchemy(app)
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(80),nullable=False)
content = db.Column(db.Text,nullable=False)
def to_json(self):
return {
'id':self.id,'title':self.title,'content':self.content
}
@app.route('/add',methods=['POST'])
def add_post():
jsdata = request.get_json()
post = Post(id=jsdata['id'],title=jsdata['title'],content=jsdata['content'])
db.session.add(post)
db.session.commit()
print('데이터베이스에 저장성공')
return jsonify(post.to_json())
@app.route('/read/<int:num>')
def read_post(num):
post = Post.query.get(num)
return jsonify(post.to_json())
@app.route('/read/<title>')
def read_post_byTitle(title):
post = Post.query.filter(Post.title==title).first()
return jsonify(post.to_json())
@app.route('/list')
def list_post():
posts = Post.query.all()
return jsonify([post.to_json() for post in posts])
@app.route('/update/<int:num>/<content>')
def update_post(num,content):
post = Post.query.get(num)
post.content = content
db.session.commit()
print('업데이트 성공')
return jsonify(post.to_json())
@app.route('/delete/<int:num>')
def delete_post(num):
post = Post.query.get(num)
db.session.delete(post)
db.session.commit()
print('삭제 성공')
return jsonify(post.to_json())
app.run(host='0.0.0.0',debug=True,port=7777)