顯示具有 flask 標籤的文章。 顯示所有文章
顯示具有 flask 標籤的文章。 顯示所有文章

2023年2月20日 星期一

Flask 2.x實作開工

hackmd的book連結

在職修課期間有幾位網友問我會不會針對2.x的部份再寫些新的東西,當初真的是心有餘而力不足,現在其實也還是,因為我在玩天堂w...

不過如何總算是開始動手了,除了重寫所用到的extension之外,題目的部份也暫定是天堂w的血盟分鑽管理,如果這個題目走不下去的話就會調整成自己寫一個記帳網頁。

會選擇血盟分鑽的題目是因為,有在玩的就知道,每一筆交易都需要手續費,過於頻繁的交易會付出過多的手續費。如果可以月結的話,那也許無形成也可以省下一筆不少的費用,因為角色之間可以互相沖帳。

當然如果真的不行的話變成是一個記帳網頁也不錯,生活中很多開銷如果可以好好記錄,回頭可以看到不少亮點。雖然現在也已經有很多的手機app可以使用,而且有更好的服務,但是寫一個專屬於自己的工具那種感覺是很不錯的。

最重要的當然就是我們可以從實作中瞭解到Flask帶給我們的便利性,然後從一個lib延伸學習到更多的lib。舉例來說,flask就單純的是flask,你想要跟資料庫對接也許就會考慮使用flask-sqlalchemy,使用flask-sqlalchemy也許你會採用orm,那你就學到orm於sqlalchemy的整合應用。

總之,還是那句話,flask是自由的,自由的意思就是很多事情你要自己處理,而不是由flask這個框架幫你決定一切。

PS: 目前已重置完成flask-sqlalchemy、flask-login


2018年11月6日 星期二

Flask + Keras = builtins.ValueError

Flask + Keras = builtins.ValueError

tags: flask keras python deep learning builtins.ValueError

在翻譯完Building a simple Keras + deep learning REST API我就馬上拿著公司的案子來測試,一切似乎都順利,因為專案啟動之後沒有任何的錯誤訊息,當我call api之後就出現異常訊息,如下:

builtins.ValueError
ValueError: Tensor Tensor("dense_3/Softmax:0", shape=(?, 6), dtype=float32) is not an element of this graph.

我在初始化的時候載入模型,在另外的module引入該模型使用model.predict,順著錯誤訊息去詢問谷狗大神得到不少解決問題的方式,但是沒有一個可以解決我的問題。我很納悶,為何我依著自己翻譯的文件執行是可以的但是實際專案卻失敗。

因此我試著不在另外的module使用該模型,而是初始化的時候就直接使用model.predict,這種方式反而可以正常的執行,然後我忘了註解掉初始化的時候所執行的model.predict又回頭去module測試model.predict,正常了:scream:。

沒錯,正常了。:weary::weary::weary::weary::weary:

就這麼歪打正著,我發現只要在初始化的時候model.predict一筆,後面就正常了,所以在load_model之後我加入model.predict(np.ones((1, ???, ???, ?))),專案就順利執行了。(???,???,?再請依著自己模型的dimension與channel調整即可。)

這個坑大概花了三個小時爬出來,也算值得了:smiley:。

2018年10月24日 星期三

Building-a-simple-Keras--deep-learning-REST-API文章翻譯

Building a simple Keras + deep learning REST API(文章翻譯)

文章來源:The Keras Blog
原文連結_Keras

這是一篇Adrian Rosebrock的客座文章,Adrian是PyImageSearch.com的作者,這是一個關於機器視覺與深度學習Blog。Adrian最近剛完成一本著作Deep Learning for Computer Vision with python,一本關於深度學習使用Keras進行機器視覺與影像辨識的新書。

在這個教學中,我們將展示一個應用Keras模型並將它佈暑為REST API的簡單方式。

本文範例將做為你建構自己的深度學習API的模板/起點,你將可以擴展程式碼並依著API端點需求的可擴展性及可靠性來自定義。

我們將學習到:

  • 如何去(如何不去)將Keras模型載入到記憶體以便可以有效率的用於推理
  • 如何使用Flask框架來建立我們的API端點
  • 如何利用我們的模型做預測,將結果以JSON-ify回傳到Client端
  • 如何利用Python與curl呼叫我們建立的Keras API

最終你將對建立Keras REST API的組件有很好的理解(最簡單的形式)

你可以隨意的使用這個指南的所有程式碼到你的深度學習REST API

注意:這邊介紹的方法用意在於教學,並不代表它可以使用於生產環境或可以負擔高承載。如果你對利用消息隊列或批處理的更高階Keras REST API有興趣,請參考A scalable Keras + deep learning REST API

設置開發環境

我們將假設你已經在你的電腦安裝並設置好Keras。如果沒有,請確保你依著官方文件說明安裝。

之後我們需要安裝Flask(以及它的相依套件),用來建立API端點的Python web開發框架。也需要request,它可以讓我們順利使用我們的API。

相關安裝命令如下:

pip install flask gvent requests pillow

建立Keras REST API

Keras REST API包含在一個單獨文件run_keras_server.py中。為了簡單起見,我們將安裝保存在單一文件中-實作起來可以更簡單的模組化。

在run_keras_server.py中你會發現三個函數,命名如下:

  • load_model: 載入Keras模型,並做好準備
  • prepare_image: 這函數用來對要透過模型預測的輸入照片做預處理。如果你不是處理影像資料,也許可以考慮將函數名稱變更為更通用的prepare_datapoint並應用任何你可能執行的資料標準化工作
  • predict: API的實際端點,它將對透過請求傳入的資料做分類並回傳結果給Client

此教學的程式碼可以在這邊找到jrosebr1_git

# import the necessary packages
from keras.applications import ResNet50
from keras.preprocessing.image import img_to_array
from keras.applications import imagenet_utils
from PIL import Image
import numpy as np
import flask
import io

# initialize our Flask application and the Keras model
app = flask.Flask(__name__)
model = None

上面程式碼主要載入需求模組以及初始化flask與Keras model

這邊我們定義load_model

  • function: load_model
def load_model():
    # load the pre-trained Keras model (here we are using a model
    # pre-trained on ImageNet and provided by Keras, but you can
    # substitute in your own networks just as easily)
    global model
    model = ResNet50(weights="imagenet")

顧名思義,這個函數負責實體化我們的結構以及從磁碟中讀取權重,為了簡單起見,我們將使用Keras已經預訓練好的ResNet50,如果你使用你自定義的模型,那你將可以調整這個函數從磁碟載入模型以及權重。

在我們對來自客戶端的任何資料進行預測之前,我們首先需要準備和資料預處理:

def prepare_image(image, target):
    # if the image mode is not RGB, convert it
    if image.mode != "RGB":
        image = image.convert("RGB")

    # resize the input image and preprocess it
    image = image.resize(target)
    image = img_to_array(image)
    image = np.expand_dims(image, axis=0)
    image = imagenet_utils.preprocess_input(image)

    # return the processed image
    return image

這個函數功能如下:

  • 接受輸入照片
  • 將照片轉為RBG(如果需要的話)
  • 調整照片尺寸為224x224(ResNet的輸入維度,如果你使用自定義模型記得調整為你個人輸入維度)
  • 通過均值減法縮放資料

同樣的,在將輸入資料傳遞到模型之前,你應該根據所需的任何預處理,縮放或標準化來修改此函數。

我們現在準備定義predict函數,此函數處理對/predict端點的任何請求。

@app.route("/predict", methods=["POST"])
def predict():
    # initialize the data dictionary that will be returned from the
    # view
    data = {"success": False}

    # ensure an image was properly uploaded to our endpoint
    if flask.request.method == "POST":
        if flask.request.files.get("image"):
            # read the image in PIL format
            image = flask.request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))

            # classify the input image and then initialize the list
            # of predictions to return to the client
            preds = model.predict(image)
            results = imagenet_utils.decode_predictions(preds)
            data["predictions"] = []

            # loop over the results and add them to the list of
            # returned predictions
            for (imagenetID, label, prob) in results[0]:
                r = {"label": label, "probability": float(prob)}
                data["predictions"].append(r)

            # indicate that the request was a success
            data["success"] = True

    # return the data dictionary as a JSON response
    return flask.jsonify(data)

dict參數data主要用來保存任何要回傳給Client端的資料,success的boolean用來做為預測成功與否的指標,我們也用這個dict參數保存輸入資料的預測結果。

接收傳入資料時我們需要檢核:

  • request method是POST(允許我們發送任意資料到這個端點,包含照片、JSON、編碼資料…等)
  • 在POST期間,照片已經寫入files

接著我們取得傳入的資料:

  • 利用PIL讀取它
  • 執行資料預處理
  • 利用網路傳輸
  • 迴圈保存結果並將資料list格式寫入data["predictions"]
  • 以JSON格式回傳結果至Client端

如果你正使用非影像資料,那你應該移除request.files並自行解析輸入資料或利用request.get_json()自動解析資料將格式轉為Python dict或是物件。此外,可以考慮參考bar-talk:processing incoming request data in flast,這是一個討論flask請求對象的基礎。

剩下要做的就是啟動我們的服務:

# if this is the main thread of execution first load the model and
# then start the server
if __name__ == "__main__":
    print(("* Loading Keras model and Flask starting server..."
        "please wait until server has fully started"))
    load_model()
    app.run()

首先我們呼叫load_model從磁碟載入Keras model

呼叫load_model是一個阻斷式作業(blocking operation),並阻止web service啟動,一直到模型完成載入。如果我們沒有確保模型完全載入記憶體,並且在啟動web service之前,那我們可能會遇到下面狀況:

  1. 一個request被POST到伺服器
  2. 伺服器接收request,預處理資料並嚐試將資料傳入模型
  3. 但模型尚未被確實的載入,我們的腳本將會異常。

當建置自定義Keras REST API時,請確保插入邏輯以保證在接受請求之前模型是載入完成並準備推理。

如何不要在REST API中載入Keras模型

你也許會嚐試將模型載入寫在predict,就像這樣:

    # ensure an image was properly uploaded to our endpoint
    if request.method == "POST":
        if request.files.get("image"):
            # read the image in PIL format
            image = request.files["image"].read()
            image = Image.open(io.BytesIO(image))

            # preprocess the image and prepare it for classification
            image = prepare_image(image, target=(224, 224))

            # load the model
            model = ResNet50(weights="imagenet")

            # classify the input image and then initialize the list
            # of predictions to return to the client
            preds = model.predict(image)
            results = imagenet_utils.decode_predictions(preds)
            data["predictions"] = []

這段程式碼意味著每來一個新的request就會重新載入一次模型,這非常低效而且可能導致你的系統記憶體不足。

如果你執行上面程式碼,你會發現你的API執行非常的慢(特別是如果你的模型很大的話),這是因為每一個request都重新載入模型造成CPU與IO顯著的開銷。

看看它如何簡單的擊潰你的伺服器記憶體,假設我們同時有N個request傳入,這代表同時會有N個模型被載入記憶體,如果你的模型非常大,像ResNet,保存了N份在記憶體,這非常容易耗盡你的記憶體。

為此,盡量避免每一個request都載入一次模型,除非你有非常具體合理的理由來做這件事。

警告:我們假設你使用的是單線程的Flask服務(預設值)。如果你佈署多線程的服務,即使使用本文討論較正常的方式,還是有可能會一次載入多個模型進記憶體。如果你考慮使用專用的伺服器,像是Apache或nginx,你應該考慮讓你的管理更具擴展性,參考scalable keras deep learning rest api

啟動Keras REST API

啟動Keras REST API服務非常簡單,開啟終端機並執行:

$ python run_keras_server.py
Using TensorFlow backend.
 * Loading Keras model and Flask starting server...please wait until server has fully started
...
 * Running on http://127.0.0.1:5000

從輸出可以看的出來,模型優先載入,接著我們可以啟動Flask服務,你可以通過http://127.0.0.1:5000來連結伺服器。然而,如果你直接將上述連結直接貼到瀏灠器,你會看到下面的圖片:

原因是因為Flask URL路由中沒有設置主頁(app.route('/')),相反的你試著直接訪問http://127.0.0.1:5000/predict,會看到如下圖片:

你將看到Method Not Allowed異常訊息,這是因為你的瀏灠器正在執行GETrequest,但你的路由僅接受POST(下一節將展示如何執行)

使用cURL來測試Keras REST API

在測試或調試Keras REST API的時候,可以考慮使用cURL(無論如何,這是一個學習如何使用的好工具)

下面的照片是我們要做分類用的,一條狗,更正確的說是一條小獵犬

我們可以使用curl將照片傳到API並找出ResNet認定的照片內容:

$ curl -X POST -F image=@dog.jpg 'http://localhost:5000/predict'
{
  "predictions": [
    {
      "label": "beagle",
      "probability": 0.9901360869407654
    },
    {
      "label": "Walker_hound",
      "probability": 0.002396771451458335
    },
    {
      "label": "pot",
      "probability": 0.0013951235450804234
    },
    {
      "label": "Brittany_spaniel",
      "probability": 0.001283277408219874
    },
    {
      "label": "bluetick",
      "probability": 0.0010894243605434895
    }
  ],
  "success": true
}

-X POST代表我們正執行一個POST request
-F image =@dog.jpg代表我們正提交表單編碼資料,image的鍵值設置為@dog.jpg的內容,@符號意味著我們希望cURL載入該影像內容並將資料傳給該request
http://localhost:5000/predict代表執行的端點

注意到該輸入照片被正確歸類到beagle,並且有99.01%的置信度,其餘的top-5預測對象與概率也包含在我們Keras REST API響應中。

在程式碼內使用Keras REST API

十之八九,你將同時向Keras REST API提交資料,並以某種方式使用回傳的預測,這需要以寫程式的方式來處理伺服器的響應。

這是一個使用Python模組request的直接過程:

  • file name: simple_request.py
# import the necessary packages
import requests

# initialize the Keras REST API endpoint URL along with the input
# image path
KERAS_REST_API_URL = "http://localhost:5000/predict"
IMAGE_PATH = "dog.jpg"

# load the input image and construct the payload for the request
image = open(IMAGE_PATH, "rb").read()
payload = {"image": image}

# submit the request
r = requests.post(KERAS_REST_API_URL, files=payload).json()

# ensure the request was successful
if r["success"]:
    # loop over the predictions and display them
    for (i, result) in enumerate(r["predictions"]):
        print("{}. {}: {:.4f}".format(i + 1, result["label"],
            result["probability"]))

# otherwise, the request failed
else:
    print("Request failed")

KERAS_REST_API_URL指向我們的端點
IMAGE_PATH指向照片路徑

使用IMAGE_PATH來載入照片,並且結構化payload給予request。

給定payload,我們可以使用request.postPOST資料到我們的端點,將.json()加入語法的最後會指示以下request:

  1. 伺服器的響應(response)必需是JSON
  2. 我們希望為我們自動解析和反序列化JSON object

一但我們得到該request的輸出,r,我們可以確認分類是否成功,並迴圈r['predictions']取得資料。

執行simple_request.py,首先要確認run_keras_server.py(即flask服務)是否啟動,在shell中執行下面指令:

$ python simple_request.py
1. beagle: 0.9901
2. Walker_hound: 0.0024
3. pot: 0.0014
4. Brittany_spaniel: 0.0013
5. bluetick: 0.0011

我們成功的利用Python呼叫了Keras REST API,並獲得模型預測結果。

這篇文章中你學到了:

  • 使用Flask Web Framework將Keras model包裝為REST API
  • 使用cURL來派送資料到API
  • 使用Python以及模組request來派送資料到端點並使用結果

該教程的程式碼可以在jrosebr1_git找到,這代表它可以用來當你的Keras REST API的基板,你可以任意修改它。

請記住,這文章中的程式碼是引導用的,並不代表它可以使用於生產環境或可以負擔高承載。

以下情況最好使用此方法:

  1. 你需要快速為你的Keras模型建立REST API
  2. 你的端點不會被重擊(負載過大的意思?)

如果你對利用消息隊列和批處理的進階Keras REST API感興趣,請參閱此blog。

如果你對該文章有任何的問題或評論,請移駕至Adrian from PyImageSearch。未來主題的建議請至Twitter上尋找Francois on Twitter

2018年2月24日 星期六

Python Flask endpoint

Python Flask endpoint

tags: python endpoint

說明

在寫登入後帳號是否啟動判斷時發現,『flask web開發』的作者在裡面用了request.endpoint條件式,讓原預計僅使用登入狀態與啟動狀態來判斷的我好奇了起來,到底在flask內endpoint是什麼!
首先,我看了一下app.route這個裝飾器。
A decorator that is used to register a view function for a  
given URL rule.  This does the same thing as :meth:\`add\_url\_rule\`  
but is intended for decorator usage::
在route這個function的說明提到,使用裝飾器的效果跟使用add_url_rule一樣,這讓我想起了一開始在學flask的時候有看到前輩寫到,flask也可以跟django一樣,將所有的route寫在一個文件中,靠的就是add_url_rule。
@app.route('/fine/<name>')
def fine(name):
    return 'My name is %s.' % name
舉例範例來說,上面這個標準寫法,也可以改寫成下面這樣
def fine(name): 
    return 'My name is %s.' % name
    
app.add_url_rule('/fine/<name>', 'fine', fine)
為什麼?
我們繼續追下去看route的內容就不難發現原因了,在route內的
def route(self, rule, **options): def decorator(f): endpoint = options.pop('endpoint', None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
第3行:如果你沒有給endpoint的話,就賦值None
第4行:調用add_url_rule這個method,那我們就看一下這個method的參數。
def add_url_rule(self, rule, endpoint=None, view_func=None, **options): """ Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint"""
rule:指路由名稱,就如同@app.route(’/abcd’)內的這個/abcd
endpoint:指endpoint,flask將view function的名稱視為endpoint
view_func:指view function,就是@app.route下的function,上例來看就是fine。
關於endpoint的部份,參數說明上提到了,沒有特別設置情況下,名稱同view function。如下可發現一二:
if endpoint is None: endpoint = _endpoint_from_view_func(view_func) options['endpoint'] = endpoint
目前為止,還是無法知道endpoint是幹嘛的,追到最後面會找到到兩句重點。
rule = self.url_rule_class(rule, methods=methods, **options) rule.provide_automatic_options = provide_automatic_options self.url_map.add(rule)
路由的部份,似乎做了一點動作,一樣的,我們追蹤url_rule_class看看。
`endpoint`
    The endpoint for this rule. 
    This can be anything. A reference to a
    function, a string, a number etc.  
    The preferred way is using a string
    because the endpoint is used for URL generation.
在class上對於endpoint的說明是,The endpoint for this rule。
這令人振奮,因為我們看到了一個關聯,接著rule被add進去了url_map,我們看url_map.add做了什麼。
def add(self, rulefactory): """Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. :param rulefactory: a :class:`Rule` or :class:`RuleFactory` """ for rule in rulefactory.get_rules(self): rule.bind(self) self._rules.append(rule) self._rules_by_endpoint.setdefault(rule.endpoint, []).append(rule) self._remap = True
從上面的說明可以看的出來,透過url_map.add,讓rule(url)與endpoint有了關聯。
第10行:_rules_by_enpoint是一個字典檔,透過字典檔記錄了rule(url)跟endpoint的關聯。
最後,我們繼續看就可以發現,做完了rule(url)與endpoint的關聯之後,flask開始處理view_function與endpoint的關聯。
if view_func is not None: old_func = self.view_functions.get(endpoint) if old_func is not None and old_func != view_func: raise AssertionError('View function mapping is overwriting an ' 'existing endpoint function: %s' % endpoint) self.view_functions[endpoint] = view_func
第6行:似乎是個字典檔,觀其說明如下:
#: A dictionary of all view functions registered.  The keys will
#: be function names which are also used to generate URLs and
#: the values are the function objects themselves.
#: To register a view function, use the :meth:`route` decorator.
self.view_functions = {}
這個字典檔,就是用來記錄endpoint與view_function的對應。
其實,如果去查詢url_for的話會發現,它的第一個參數放的是endpoint,那也可以明白為什麼可以利用url_for(‘view_function’)來回到route,因為其實是url_for(‘endpoint’)。
直觀的理解就是,flask透過了endpoint來記錄了跟rule(url)與view_function的關聯,所以有endpoint,就有辦法找到相關的rule與view_function。
因此,透過了url_for有辦法直接的尋找到相對應的route與view_function,以及利用route能夠找到相對應的view_function。

範例

知道了道理,就可以開始寫一個測試程式確認我們心中的想法。
首先,我們設置一個route
@app.route('/urlroot', endpoint="root") def func_root(): # print(url_for('func_root')) 先註解掉這行 print(url_for('root')) print("View function: {view}. Endpoint: {endpoint}".format(view="func_root", endpoint=flask.request.endpoint))
第1行:指定endpoint為root
第4行:利用url_for來看root會定位到那
第5行:列印request.endpoint確認
得到的結果如下:
/urlroot
View function: func_root. Endpoint: root
可以確認到,利用endpoint我們確實的找到了rule,來源request.endpoint為root。
接著註解掉print(url_for(‘root’)),改換用view_function做參數測試,這時候得到的回應是一個錯誤,利用view_function是沒有辦法找到相對應的rule。

在查詢資料的期間也學習到另一種方式
# 新增一個rule,但不指定view_function app.add_url_rule(rule='/rule', endpoint="enpo", methods=["GET", "DELETE"]) # 手動讓endpoint跟view_function關聯,就跟我們操作dict一樣,加入而以。 app.view_functions['enpo'] = func_root
第1行:手動加入路由,但不指定view_function
第4行:手動關聯endpoint與view_function
得到的結果如下
View function: func_root. Endpoint: enpo
一個路由,可以讓多個endpoint去關聯。
以上學習記錄。

學習參考

stackoverflow
stackoverflow翻譯_感謝對岸同好
對岸討論區_segmentfault
這篇的案例可以讓我們更直觀的理解到endpoint的用途。

2017年9月10日 星期日

Python Flask.Blueprint

Python Flask.Blueprint

簡單

Blueprint可用來設置route,專案只要一大,整個api或是web的route就會跟著複雜。
總不可能把所有的route都設置在同一支程式上,這樣子對整個專案的維護性過低。
不過如果你只有一個api的話…記得就放同一支就好了!

範例

主程式
#  __init__.py

from flask import Flask
from manu import testRoute

app = Flask('__name__')
app.register_blueprint(testRoute)

if __name__ == '__main__':
    app.run(debug=True)
生產用route
#  manu.py

from flask import Blueprint
testRoute = Blueprint('testRoute', __name__)

@testRoute.route('/manu/manu1')  #  路由上標名了生產
def testroute():
    return '<h1>You win!</h1>'

@testRoute.route('/manu/manu2')  #  路由上標名了生產
def testroute2():
    return '<h1>You win2!</h1>'

@testRoute.route('/manu/manu3')  #  路由上標名了生產
def testroute3():
    return '<h1>You win3!</h1>'
連結網址
http://127.0.0.1:5000/manu/manu1

加上前綴

你要建構的是一個讓很多route可以清楚分開交通網是吧。
這是一個生產用的route,以後會有財務、業務…等,沒錯吧!
所以我們希望這個路由是區隔而且明確的。
可是你不可能吃飽閒閒每一個路由都寫著’/manu/xxx’,’/manu/yyy/’…
太不科學了,所以我們就會需要用到url_prefix了!
註冊url_prefix有兩個方式,一個是在產生Blueprint物件的時候給,一個是在註冊的時候給!
#  產生物件的時候
testRoute = Blueprint('testRoute', __name__, url_prefix='/manu')
#  註冊blueprint的時候
app.register_blueprint(testRoute, url_prefix='/manu')
基本上,原廠建議是在註冊的時候再給,日後好維護。

範例

要來調整一下我們的程式…
#  __init__.py

from flask import Flask
from manu import testRoute

app = Flask('__name__')
app.register_blueprint(testRoute, url_prefix='/manu')

if __name__ == '__main__':
    app.run(debug=True)
from flask import Blueprint
testRoute = Blueprint('testRoute', __name__)

@testRoute.route('/manu1')  #  路由拿掉剛才標上的生產
def testroute():
    return '<h1>You win!</h1>'

@testRoute.route('/manu2')  #  路由拿掉剛才標上的生產
def testroute2():
    return '<h1>You win2!</h1>'

@testRoute.route('/manu3')  #  路由拿掉剛才標上的生產
def testroute3():
    return '<h1>You win3!</h1>'
連結網址
http://127.0.0.1:5000/manu/manu2
這樣,程式碼是不是優美多了!