1. 程式人生 > >Flask Hello World 入門

Flask Hello World 入門

  1. 先安裝 python3.x 環境, 如果你還沒安裝過的話.

在這裡插入圖片描述

把下面的程式碼儲存為 init.sh
然後 chown +x init.sh

#!/usr/bin/env bash
#確保shell 切換到當前shell 指令碼資料夾
current_file_path= ( c d "

(cd " (dirname “$0”)"; pwd)
cd ${current_file_path}

rm -rf flask_tutorial
pwd;ls;
mkdir -p ${current_file_path}/flask_tutorial/flask/app/templates; cd ${current_file_path}/flask_tutorial;
virtualenv -p python3 --no-site-package venv
source venv/bin/activate
pip install flask

cd ${current_file_path}/flask_tutorial/flask/app;
touch init.py
touch routes.py
touch myblog.py

cat << EOF >> init.py
from flask import Flask
#建立app應用,__name__是python預定義變數,被設定為使用本模組.
app = Flask(name)
from app import routes
EOF

cat << EOF >> myblog.py
#從app模組中匯入app應用
from app import app

#防止被引用後執行,只有在當前模組中才可以使用
if name==‘main’:
app.run()
EOF

cat << EOF >> templates/index.html

{{ title }} - 部落格

Hello ,{{ user.username }},現在時間是:{{timenow.whattime}}!

EOF

#下面這個把上面的route.py 覆蓋了.
cat << EOF >> routes.py
#匯入模板模組
import time;
from flask import render_template
from app import app

@app.route(’/’)
@app.route(’/index’)
def index():
user = {‘username’:‘開心’}
timenow={‘whattime’: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}
#將需要展示的資料傳遞給模板進行顯示
#return render_template(‘index.html’,title=‘我的’,user=user)
return render_template(‘index.html’,title=‘我的’,user=user,timenow=timenow)
EOF

export FLASK_APP=myblog.py
flask run