Day 56 - Flask


Posted by pei_______ on 2022-06-03

learning from 100 Days of Code: The Complete Python Pro Bootcamp for 2022


flask documentation
HTML5 UP - 免費模板

  • python上搜尋+取代快捷鍵: ctrl + r
  • chrome開發者工具設定網頁可更改: console > document.body.contentEditable=true

Flask基礎架構

from flask import Flask

# __name__: whay is current class, function, method,descriptor, or generator instance

app = Flask(import_name=__name__)
print(__name__)


# '/': navigate to homepage
# @app.route('/'): python decorators - only trigger wrapped function if user access '/'

@app.route('/')
def hello_world():

    return '<h1 style="color: red;">Hello, World!</h1>' \
           '<p>This is a paragraph.</p>' \
           '<a href="https://www.google.com/">link</a><br>' \
           '<img src="https://media.giphy.com/media/3oriO0OEd9QIDdllqo/giphy.gif">'


#---  Different routes using ---#

@app.route('/bye')
def bye_world():
    return '<h1>Bye</h1>'


#---  Create variable path and converting to a specified data type ---#

@app.route('/username/<name>/<int:number>')
def greet(name, number):
    return f'<h1>Hello {name}. You are {number} years old.</h1>'



if __name__ == "__main__":

    # Run app in debug mode to auto-reload
    app.run(debug=True)

在Flask中插入 HTML / CSS / img

重點在於"資料放置的位置"與"檔案夾名稱"

01. main.py

02. tamplates (放置HTML檔)
ex. index.html

03. static (放置css, jpg等其他檔案)
ex. styles.css
ex. image.jpg

# main.py

from flask import Flask, render_template

app = Flask(import_name=__name__)


@app.route('/')
def home_page():
    # automatic find 'templates' folder next main.py
    return render_template('index.html')


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

// index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Penny</title>
    <link rel="stylesheet" href="static/styles.css">
</head>
<body>
    <h1>I'm Penny</h1>
</body>
</html>

#Python #課堂筆記 #100 Days of Code







Related Posts

Flex-grow / Flex-shrink / Flex-basis

Flex-grow / Flex-shrink / Flex-basis

【Day 3】Docker Container(容器)與 Volume(數據卷)

【Day 3】Docker Container(容器)與 Volume(數據卷)

Linear Kalman Filter 筆記

Linear Kalman Filter 筆記


Comments