TIL/Python

[Python][Flask] 플라스크 이용하기 - 3.렌더링 & 꾸미기

탱! 2022. 5. 18. 16:15

1. URL Building :  the url_for() function 

웹사이트 안에 url 집어 넣기

 

일일이 코드를 작성하는 것보다

<a href='url주소 일일이/함수주소/<변수값>'>주소1</a>

url_for() 함수를 이용하면 좋은 이유

<a href={{url_for('라우터밑에 함수이름',변수=데이터값)}}></a>

1) 더 알기 쉽다.

2) 수정하기 쉽다.

3) 특정 문자를 (예를 들면 대문자 소문자 변환과 같은 것) 수정하기 쉽다.

4) 절대경로를 생성하며 불확실한 경로를 피한다.

5) 만일 앱이 url root밖에서 생성 되면 도와준다.(?)

 

이전에 사용했던 코드를 연이어 사용해보자

with app.test_request_context():
    print(url_for('show_post',post_id=20220516,number=34))
    print(url_for('hello_world2',name='tae'))

/post/20220516/34

/tae

 

 

2. HTTP Methods

웹 애플리케이션은 url에 접근할 때 다른 http 메소드를 사용한다.라우트는 GET requsets에만 반응하며 라우트의 인자로 메소드를 사용할 수 있다. GET/POST/HEAD/OPTIONS

from flask import request

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

3. Static Files

css 나 javascript같은 파일을 이용해서 웹을 동적으로 꾸밀 수 있다.

파일안에 tatic이라 불리는 폴더를 만들고 그안에 css을 만든다.

후에 사용하게될 html 에 

url_for('static', filename='style.css')

을 이용해서 아래와 같이 사용한다.

<link href="{{ url_for('static', filename='style.css') }}" rel="stylesheet">

4. Rendering Templates

1) html 파일

 render_template()method을 이용해서 템플릿을 렌더할 수 있다. 템플릿의 이름과 핵심인자로 템플릿엔진을 패싱할 변수만 있으면 된다.

from flask import Flask,render_template

app=Flask(__name__)

@app.route('/')
def hello_world():
    return render_template('index.html')

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

중요한것은 같은 폴더안에 새로 templates라는 폴더를 만들고 그곳에 html파일을 생성한다.

<!DOCTYPE html>
<html lang="'en">
    <head>
        <meta charset="utf-8">
        <title>Hello World</title>
    </head>
    <body>
        <h1 style="color:darkolivegreen">Hello World!</h1>
        <p style="color:coral">This is me!</p>
    </body>
</html>

이런 파일을 만들면 웹의 홈에 위와 같은 html이 적용된다.

 

2) css 파일 

css 파일이 있어야 할 곳은 서버파일 있는곳에 새로운 static 폴더를 만들어서 저장하고

html의 링크에 /static/style.css 로 불어오면 된다.

css파일을 그냥 두었을 때와 css파일을 static폴더에 두고 html의 css 링크 수정

이때 크롬은 정적파일(스타일 시트,이미지 자바스크립트)을 캐시한다.

 한번 브라우저가 다운로드한 이상 계속 유지하려고 하기 떄문인데

shift 하고 새로고침하면 업그레이드 된다.

 

4.템플릿이용하기

https://nicepage.com/html-templates

 

10,000+ Free HTML Templates. HTML Website Templates

Free Download the biggest collection of HTML templates. HTML website template code. Freely use basic and simple HTML templates for your commercial or personal use.

nicepage.com

이런 웹에서 무료로 제공하는 파일을 다운 받아서 사용하는 것도 방법이다.

그리고 파일을 적재적폴더에 넣어야한다는 것도!

저작권 명시를 잊지말자!

 

doucment.body.contentEditable=true

을 웹개발자 도구 콘솔에 입력하면 수정할 수 있다.

그러고 페이지 저장을 누르고 파일을 다시 잘 놓고 수정하면 된다.