Programming/Python

Python 5강 - Web에서 구동

상맹 2021. 9. 13. 22:44
반응형

1. Flask 

  → from flask import Flask 입력후 실행해서 있는지 Flask 라이브러리 확인

 

 * 템플릿 엔진 : html에 자기언어를 쓸수 있게 해주는 것, 동적인 응답을 하게 해준다.(하나의 페이지를 동적 전달)

 - Jsp : java 코드 html에 쓸 수 있다. 

 - Asp : C 코드 html에 쓸 수 있다.

 

  ① TERMINAL 창에 pip install flask 입력

  ② html 만들기, 환경설정

MagicPython → HTML로 변경

 

예제 ①

from flask import Flask
app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello World!"


if __name__ == "__main__":
    app.run()

localhost:5000 입력 하면 -> Hello World 출력가능

 

예제 ① 에 /hello, /bye 추가, port 이름 변경, host 변경

from flask import Flask
app = Flask(__name__) # __name__ 자기 자신이 실행되었을때 __main__


@app.route("/hello")
def hello():
    return "Hello World!"


@app.route("/bye")
def bye():
    return "Bye!!"


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=3500)

localhost:5000 변경 전
localhost:3500으로 변경 후

 * __name__은 자기 자신이 실행 되었을 때, __main__, import시에는 파일명 호출

 * app.run에서 host는 해당 호스트에게 실행 권한을 준다.

 * 0.0.0.0은 모든 호스트가 가능(모든 IP(요청)를 받겠다.), port는 해당 port지정한다. 

 * @app.route(Anotation)를 이용하여 함수를 return 했을 때 데이터가 return 된다.

 

2. Jinja2 : 플라스크 설치 시 자동으로 설치

 

Jinja 템플릿 문법

Jinja는 flask가 기본적으로 지원하는 템플릿엔진이다.

gunbin91.github.io

3. 연습문제 : 지난 시간에 사용한 영화 데이터 가져와서 웹에 띄우기

 

파이썬 4강 - 통신

pip --version : 환경변수가 잡혀 있는지 확인 할수 있다. pip install requests : 파이썬 모듈인 requests 설치(라이브러리), 통신을 위해선 무조건 필요 requests Python HTTP for Humans. pypi.org 사이트에..

sangmaeng.tistory.com

다음과 같이 파일 생성

- static 파일 : css, javscript, image 정적 파일 넣는 폴더

- templates 파일 : template 파일, 진짜 투엔진이 해석할수 있는 파일 폴더

 

① router.py 생성

from flask import Flask
from flask.templating import render_template
import movie_api as ma

app = Flask(__name__)


@app.route("/")
def index():
    # flask는 template안에 있으면 무조건 해석해준다. # render_template 입력시 자동으로 import된다.
    return render_template("index.html", movies=ma.CallMovieApi())


if __name__ == "__main__":
    app.run(debug=True)

* render_template에서 앞은 key 값, 뒤는 value 

* view resolver가 알아서 template를 찾아가준다. prefix는 templates로 잡혀있지만 suffix는 설정 해줘야한다.

* app.run(debug=True) → 저장 시 자동으로 서버 리로딩 된다!

 

② movie_api.py 생성

  CallMovieApi(): 함수 호출

import requests


def CallMovieApi(page=1):

    url = f'''
        https://yts.mx/api/v2/list_movies.json?sort_by=rating&page_number={page}&limit=20
    '''
    response = requests.get(url)

    responseDict = response.json()  # 딕셔너리 타입으로 변환
    movies = responseDict["data"]["movies"]  # list 타입

    return movies

* f 주소에 페이지 변수를 넣기 위해서 사용한다. → 호출 할 때마다 페이지를 바꿔서 호출 가능하다.

 

 

③ index.html 생성

 - Bootstrap 4 Cards 사용

 

Bootstrap 4 Cards

Bootstrap 4 Cards Cards A card in Bootstrap 4 is a bordered box with some padding around its content. It includes options for headers, footers, content, colors, etc. John Doe Some example text some example text. John Doe is an architect and engineer See Pr

www.w3schools.com

  - 문법 {% for %}문 , {% endfor %}를 사용

<!DOCTYPE html>
<html lang="en">

<head>
    <title>영화리스트</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <style>
        .m_box {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            grid-gap: 10px;
        }

        .m_tm_20 {
            margin-top: 20px;
        }
    </style>
</head>

<body>

    <div class="container m_box m_tm_20">

        {% for movie in movies %}
        <!-- 영화 카드 시작 -->
        <div class="card">
            <img class="card-img-top" src="{{movie.medium_cover_image}}" alt="Card image" style="width:100%">
            <div class="card-body">
                <h4 class="card-title">{{movie.title}}</h4>
                <p class="card-text">평점 : {{movie.rating}}</p>
                <a href="#" class="btn btn-primary">상세보기</a>
            </div>
        </div>
        <!-- 영화 카드 끝 -->
        {% endfor %}

    </div>

</body>

</html>

④ 결과값

 

반응형

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

Python 7강 - HTML Parsing  (0) 2021.09.22
Python 6강 - Crawling  (0) 2021.09.20
Python 4강 - 통신  (0) 2021.09.13
Python 3강 - Class, 생성자, Exception  (0) 2021.09.13
Python 2강 - list, tuple, dictionary, if, function 특징, import  (0) 2021.09.13