본문 바로가기
Python/Flask Server

Flask에서 form으로 데이터 전송하기 [ form action / 딕셔너리명.items() / input required name ='데이터명' / request.form['데이터명'] / jinja2 Syntax ]

by leehii 2022. 7. 18.

main.html : 메인페이지

result.html : 데이터를 전송받는 페이지

 

-----main.html-----

 

<div class='class명'>

  <h1>제목<h1>

    <form action = '/result.html' method='post'>                                                            

       <select required name='name명' onchange='this.form()'>   

         <option value="value값1">내용1</option>

         <option value="value값2">내용2</option>

         <option value="value값3">내용3</option>

    </form>

 

 

-->> main page 의 div class의 값들을 post방식으로 result.html 파일로 보내준다

-->> 이때 보내는 값들은 name명 혹은 value값등에 있다

 

----------result.html----------

 

<body>

    <table>

        {% for key, value in result.items() %}

        <tr>

            <th>{{key}}</th>

            <td>{{value}}</td>

        </tr>

        {% endfor %}

    </table>

</body>

 
 
 

-->> form 방식 : data의 형태가 딕셔너리

-->> 따라서 items()를 통해 key값과 value값이 출력 가능함

 

-->>  jinja2 는 flask server 에서 WebPage 로 값을 보낼때 사용하는 것

 

( ex )

{{ flask에서 보낸 값}}      /     {% 문법(if 혹은 for)  사용 %}

이 두가지로 구성됨

 


일반적인 형식
    
{% if문 or for문 %}
    
    {{ 변수나 표현식}}
     ... ....
{% endif 또는 endfor %}

 

 

 

----------flask.ipynb----------

from flask import Flask, render_template, request

 

app = Flask(__name__)

 

@app.route('/')

 

def main():

  return render_template('main.html')

 

@app.route('/result', method = ['POST','GET'])

 

def result():

  if request.method == 'POST' :

    result = request.form

    return render_template('result.html', result=result)

 

 

if _ _name_ _ == " _ _main_ _ " :

app.run ()

 

 

 

 

-->> def main은 그냥 main.html을 실행하는 함수

-->> def.result는 result.html을 실행하는 함수

-->> reques. form으로 모든 데이터를 전송함

       / 특정데이터만 원하면 result = request.form['name']등으로 처리하면 가능함

 

 

 

------------------------------------------------------------------------------------------------------

 

@app.route('/crawling',methods = ['POST' ,'GET'])

def crawling():

 

    if request.method == 'POST':

        START = request.form['from']  

        START = str(START)

-->> main.html에서 required name = 'from'으로 지정된 값을

        플라스크 서버에서 request.form['from'] 으로 from이라는 특정값만 가져와서

        START라는 변수에 담음

 

        required는 input태그에서 form data를 서버로 전송할때 입력해야 하는 필드

        text, password, radio,checkbox, date, email, file, search등등에서 사용가능

 

 

    END = request.form['to']

        

    END = str(END)

-->> main.html에서 required name = 'to''으로 지정된 값을

        플라스크 서버에서 request.form['to'] 으로 to라는 특정값만 가져와서 END라는 변수에 담음

 

       
 

        url = '크롤링할 주소' 

        driver = webdriver.Chrome('크롬드라이버 위치')

        driver.get(url) 

        driver.implicitly_wait(time_to_wait=10) 

 

        # 출발지 도착지

 

        start = START

        end = END

 

       driver.find_element(By.XPATH, XPATH값).send_keys(start)

       driver.find_element(By.XPATH, XPATH값).send_keys(end)

 

 
 
 
 

 

-->> input으로 직접 vscode에서 입력받아서 크롤링하던 것을 

          이런식으로 플라스크 서버의 변수를 이용해 크롤링 가능!