서버에 파일 저장, DB에 이름을 저장해 꺼내쓸 때를 위한 서버 코드를 만들어보았다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 
import os
import random
import string
import requests
from flask import Flask, render_template, request, jsonify, redirect, session
 
 
@app.route("/post", methods=["POST""GET"])
def post():
    # 요청은 form에서 동기화 방식으로 처리됩니다. form 속성의 enctype을 file 전송에 적합한 multipart/form-data으로 변경해주세요.
    # 비동기 처리를 원하면 ajax 같은거 쓰셈
    if request.method == 'POST':
 
        # file은 request.files로 받아 옵니다
        title_receive = request.form['title']
        desc_receive = request.form['desc']
        writerid_receive = request.form['writerid']
        star_receive = request.form['star']
        file_receive = request.files['file']
 
        path = "./static/images/"
 
        # 파일 이름에 랜덤 문자열 삽입
        length_of_string = 8
        random_string = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length_of_string))
        receive_filename = file_receive.filename
        index_temp = receive_filename.find(".")
        filename = receive_filename[:index_temp] + random_string + receive_filename[index_temp:]
 
        # 이미지 업로드 경로가 존재 하지 않을 경우 생성
        if not os.path.exists(path):
            os.mkdir(path)
 
        # 설정한 저장 경로에 파일 이름으로 저장
        file_receive.save(path + filename)
 
        # DB에 보낼 데이터 dict 저장
        doc = {
            'title': title_receive,
            'desc': desc_receive,
            'writerid': writerid_receive,
            'star'int(star_receive),
            'file': filename
        }
 
        # DB에 저장
        db.posting.insert_one(doc)
 
        success_msg = "포스팅 완료되었습니다"
 
        return render_template("gangneung/post.html", success_msg=success_msg)
 
    return render_template("gangneung/post.html")
 
cs

 

파일 네임을 경로로 만들어 나쁜 짓을 꾸미는 못된 악당을 막으려면

from werkzeug import secure_filename

라이브러리 넣어주고

파일 이름에 랜덤 문자열 삽입해주기 전에 secure_filename(filename) 을 쓰면 된다

특문 같은걸 마음대로 바꿔버리는 메소드이니 몇 번 테스트해보길 권장

 

string.ascii_letters는 아스키 코드에 기반한 a-f, A-F 가 문자열로 들어있다 (아스키 기반이기에 로컬 설정에서 자유롭다)

string.digit은 0~9 들어있는 배열이고 그 둘을 합쳐서 문자열로 만든담에 random.choice 메소드로 한개씩 야무지게 뽑아낸다

 

하지만 이렇게 작성하면 "."이 여러개 들어간 파일의 경우 처리가 안되므로 rfind() 서비스메소드를 활용해 마지막 "."을 가져오는 방법을 사용하면서 조건문으로 확장자 타입을 처리해줘야 한다

 

참고 : https://docs.python.org/ko/3/library/string.html?highlight=string#module-string

 

이_언어는_+_하면_왠만하면_되서_신기해

 

'Development > Python' 카테고리의 다른 글

pymongo로 mongoDB objectId 사용하기  (0) 2022.09.03
반복문 돌려가며 Dictionarys in Array 로 만들기  (0) 2022.08.28
Flask session 사용  (0) 2022.08.21
git-bash 서버 환경설정 (ubuntu, python-flask)  (0) 2022.07.24
Flask  (0) 2022.07.23

+ Recent posts