flask에 있는 @app.route는 templates라는 폴더 안에 있는 파일만 연결할 수 있다.

- write.html 소스
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table>
<form name="form" method="post" action="write">
<tr><td>작성자</td>
<td><input type="text" name="name"></imput></td></tr>
<tr><td>제목</td><td><input type="text" name="title"></td></tr>
<tr><td>내용</td><td><textarea name="contents"></textarea></td></tr>
<tr><td><input type="submit"></imput></td></tr>
</form>
</table>
</body>
</html>
- run.py 소스
from flask import Flask, request
from flask import render_template
from flask_pymongo import PyMongo
from pymongo import MongoClient
app = Flask(__name__)
mongo = PyMongo()
client = MongoClient('mongodb://localhost', 27017) # 로컬환경에서 mongo db 연결
# client = MongoClient('mongodb://test:test@localhost', 27017) # db 인증 계정 생성 후 연결 방법
# neuruWeb = 스키마 이름을 느루웹으로 만듬
db = client.neuruWeb
@app.route('/')
def home():
return 'This is home!'
# db write 부분 write.html에서 post로 보낸 데이터 받아서 db에 저장
@app.route('/write', methods=["GET", "POST"])
def board_write():
if request.method == "POST":
name = request.form.get("name")
title = request.form.get("title")
contents = request.form.get("contents")
print(name, title, contents)
doc = {
"name": name,
"title": title,
"contents": contents,
}
# db = neuru web 이라는 스키마임, 스키마 아래에 board라는 컬랙션을 생성후 데이터를 넣음
db.board.insert_one(doc)
return render_template("write.html")
else:
return render_template("write.html")
if __name__ == '__main__':
app.run('0.0.0.0', port=5000, debug=True)
flask 서버 실행 --> python run.py

http://localhost:5000/write 에 접속 후 데이터 입력

Robo 3T 확인

데이터가 잘 들어왔다.
'study > flask' 카테고리의 다른 글
[flask] include -- html header, footer등 중복되는 html 처리 (0) | 2021.10.24 |
---|---|
[vs code] flask + mongoDB 연결(Read) (0) | 2021.10.24 |
[vs code] flask + mongo DB(설치, Robo 3T 연결) (0) | 2021.10.24 |
[vs code] Python flask 서버 구축 (0) | 2021.10.23 |