參考 – https://jeffwen0105.com/%E7%AC%AC%E4%B8%80%E6%AC%A1%E4%BD%BF%E7%94%A8-python-flask-restful-api-%E5%B0%B1%E4%B8%8A%E6%89%8B-get-%E6%96%B9%E6%B3%95/ 使用 Flask 模組物件提供的函數來建立 API(Application Programming Interface) .
測試環境為 CentOS 8 x86_64
所需套件 Flask
[root@localhost ~]# pip3 install Flask
API 程式:
[root@localhost ~]# vi api.py from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "<h1>Hello , This a Restful Api Server by Flask...</h1>" app.run(port=8088, debug=True)
程式說明 :
- from flask import Flask
載入 Flask 套件. - app = Flask(__name__)
建利 Flask 物件. - @app.route(“/”)
def hello():
return “<h1>Hello , This a Restful Api Server by Flask…</h1>”
建立根目錄路由,這語法應該是 singledispatch decorator – https://benjr.tw/103440 之後我們可以依需求建立不同的目錄路由.
該路由下只有一個 hello 函數(回傳 html 格式的資料). - app.run(port=8088, debug=True)
監聽 8088 埠 , 並使用除錯模式.
執行結果
伺服器端透過 Python 執行該程式.
[root@localhost ~]# python3 api.py * Serving Flask app 'api' (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:8088/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 346-995-186
以下是在 Linux 下,透過 curl (文字版的遊覽器) 執行,來檢視一下 API : http://127.0.0.1:8088/
[root@localhost ~]# curl http://127.0.0.1:8088/ <h1>Hello , This a Restful Api Server by Flask...</h1>
沒有解決問題,試試搜尋本站其他內容