공부/Flask
[Flask] 파일 업로드/삭제/수정
래울
2021. 10. 4. 14:06
write.html(거의비슷update.html)
<!DOCTYPE html>
<head>
<!--css -->
<link rel="stylesheet" type="text/css" href="/static/css/styles.css">
<!-- ckeditor -->
<script src="/static/ckeditor5/ckeditor.js"></script>
<style>
.ck-editor__editable {
min-height: 400px;
}
</style>
</head>
<body>
<div class="container">
<br>
<h3>포스트 작성하기</h3><br>
<form name="frm_pw" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="title">* 제목</label>
<input type="text" name="title" class="form-control" placeholder="제목을 입력하세요">
</div>
<div class="form-group">
<br>
<label for="title">* 비밀번호</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<br>
<label for="title">타이틀사진</label>
<input type="file" name="title_image" class="form-control">
</div>
<div class="form-group">
<br>
<label for="content">* 내용</label>
<textarea name="contents" id="editor" class="form-control" placeholder="내용 입력"></textarea>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ), {
language : {ui: 'ko', content: 'ko'}
// toolbar: [ 'heading', '|', 'bold', 'italic', 'link' ]
} )
.then( editor => {
window.editor = editor;
} )
.catch( err => {
console.error( err.stack );
} );
</script>
</div>
<br>
<input style="font-size:100%; border:2px solid black; border-radius: 0.25rem;transition:box-shadow 0.15s ease-in-out;" type="submit" class="btn-primary">
</form>
</div>
</body>
write python 부분
@main.route('/write', methods=['GET','POST'])
def write():
if 'userid' not in session:
#print("비로그인 상태")
return "<script>alert(\'로그인 후 이용하세요.\');document.location.href=\"login_service/login\"</script>"
if request.method == 'GET':
return render_template('/main/write.html')
#print("로그인 상태")
title = request.form['title']
password = request.form['password']
contents = request.form['contents']
if title=='' or password=='' or contents=='':
return "<script>alert(\'* 은 필수입력입니다.\');document.location.href=\"/write\"</script>"
#파일 업로드
titleimg = request.files['title_image']
fn = secure_filename(titleimg.filename)
if not fn: #파일이 없으면
fn = 'dummy-image.jpg'
else:
######같은 이름 파일 업로드 중복처리.
_ = 0
while os.path.isfile("app/static/img/"+fn):
fn = str(_)+fn
_ += 1
titleimg.save(os.path.join('app/static/img/'+ fn))
#print(title,password,contents,request.remote_addr,session.get('userid'))
db_class = dbModule.Database() #db연결
userid = session.get('userid')
sql = "SELECT name from user where id=%s;"
username = db_class.executeAll(sql, userid) #username 받아오기
sql = "INSERT INTO board (pwd, name, title, content, ip, viewcnt, titleimg) VALUES (%s, %s, %s, %s, %s, %s, %s);"
args = (password, username[0]['name'], title, contents, request.remote_addr, 0, fn)
#print(args)
boards = db_class.executeAll(sql, args)
db_class.commit()
return redirect('/')
update python부분
## 글 수정하기
@main.route('/update', methods=['GET','POST'])
def update():
if 'userid' not in session:
#print("비로그인 상태")
return "<script>alert(\'로그인 후 이용하세요.\');document.location.href=\"login_service/login\"</script>"
#print("로그인 상태")
db_class = dbModule.Database() #db연결
bid = request.args.get('bid')
if request.method == 'GET':
if request.args.get('bid')!=None and bid!='':
sql = "SELECT * FROM board WHERE id=%s;"
old_board = db_class.executeAll(sql, bid)
return render_template('/main/update.html', old_board=old_board[0])
# POST
title = request.form['title']
contents = request.form['contents']
password = request.form['password']
if title=='' or password=='' or contents=='':
return "<script>alert(\'* 은 필수입력입니다.\');window.history.back();</script>"
sql = "SELECT pwd, titleimg FROM board WHERE id=%s;"
old_board = db_class.executeAll(sql, bid)
if old_board[0]['pwd'] != password:
return "<script>alert(\'비밀번호가 일치하지않습니다.\');window.history.back();</script>"
titleimg = request.files['title_image'] #파일 업로드, 글 수정시 이전파일 삭제 후 업로드
fn = secure_filename(titleimg.filename)
print(old_board, fn, titleimg.filename)
if old_board[0]['titleimg']!=''and old_board[0]['titleimg']!=None and old_board[0]['titleimg']!='dummy-image.jpg' and fn: #이미 파일이 있을때 업로드
os.remove('app/static/img/' + old_board[0]['titleimg'])
######같은 이름 파일 업로드 중복처리.
if fn:
_ = 0
while os.path.isfile("app/static/img/"+fn):
fn = str(_)+fn
_ += 1
titleimg.save(os.path.join('app/static/img/'+ fn))
sql = "UPDATE board SET title=%s, content=%s, titleimg=%s WHERE id=%s;"
args = (title, contents, fn, bid)
else:
sql = "UPDATE board SET title=%s, content=%s WHERE id=%s;"
args = (title, contents, bid)
boards = db_class.executeAll(sql, args)
db_class.commit()
sql = "SELECT * FROM board WHERE id=%s;"
board = db_class.executeAll(sql, bid)
return render_template('/main/board.html', board=board[0], num=bid)