본문 바로가기
카테고리 없음

웹개발_4주차_개발일지

by jung1911 2023. 3. 19.
내가새로배운것!

 

 

flask

flask 시작 코드 (app.py)  flask 를 실행시킬 가장 기본이 되는 python 파일 이름을 app.py라고 한다.

flask 기본코드!

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
   return 'This is Home!'

if __name__ == '__main__':  
   app.run('0.0.0.0',port=5000,debug=True)

 

@app.route('/') 여기에 ('/mypage') 라는 명칭을 주면 라이브 서버에 /mypage를 주면

아래와 같이 나온다

 

 

 

 

HTML과app.py 연동하기

1. 폴더를 새로 만든다 (templates)
2. 폴더안에 index.html를 만들어준다
3.index.html(html) 파일을 버튼에 넣어주면 된다
4. render_template flask 기본 코드에 첫번째 from flask import Flask, render_template
이렇게 넣어준다

10번째 줄 보면 index.html 과 연동하기위해 넣어줬다라고 생각하면된다.


5.return '<button>버튼입니다</button>' → return render_template('index.html ')

 

localhost5000: (라이브서버)
html가  API를 부르고 받기  - 받는건 Fecth 

 

get 요청 API 코드

request. jsonify의 값을 넣어준다(Post도 같다)
여기다.

app.py에서 html 데이터를 내려줄때 빨간줄 처럼 해준다.

 

 

GET 요청 확인  Fetch 코드

 

fetch("/test").then(res => res.json()).then(data => {
		console.log(data)
})

 

Post 요청 API

@app.route('/test', methods=['POST'])
def test_post():
   title_receive = request.form['title_give']
   print(title_receive)
   return jsonify({'result':'success', 'msg': '이 요청은 POST!'})

Post 요청 Fetch 코드

 

post는 formData하는 데이터를 실어서 보낸다!

let formData = new FormData();
formData.append("title_give", "블랙팬서");

fetch("/test", { method: "POST", body: formData }).then(res => res.json()).then(data => {
    console.log(data)
})

연결

html에서 app.py로 보내준다.
title_receive 에 보낸값을 넣어준다.!
data에 fetch의 결과가 담긴다. result':'success', 'msg': '이 요청은 POST! 이값이 담긴거다!

TIP+

폴더 파일 이동시
디버거 핀 커서가 움직이면
ctrl + c 로 꺼준다(locall host:5000안들어가진다)

 

 

 

 

og

크롤링 기본코드에 이미지에 관련된 코드를 넣어주면 된다! app.py연결해주기

 

댓글