[ DevOps ] ngrok 與 Python Flask 整合

開發網頁或服務的時候,如果沒有 Public IP (例如:http://localhost ),但又想讓別人看到此網頁或服務時,就可以使用 ngrok 的服務讓別人連進來。


Setup ngrok

  • Download ngrok
  • unzip ngrok
    • Mac OS unzip /path/to/ngrok.zip
    • Windows 請使用解壓縮軟體

Python

  • 透過 Python Flask 建立 CRUD API
from flask import Flask  
from flask import json  
from flask import Response  
from flask import request

inet_addr = "127.0.0.1"  
app = Flask(__name__)

# *****************************************************************************************
# Create POST http://127.0.0.1:5000/api/v1.0/print
# *****************************************************************************************
@app.route("/api/v1.0/print", methods=['POST'])
def postMethod():  
    value = request.form['name']
    print "form_value: " + value
    return json.dumps({"status": 200, "comment": "[ POST Method ] Hello " + value})

# *****************************************************************************************
# Read GET http://127.0.0.1:5000/api/v1.0/print
# *****************************************************************************************
@app.route("/api/v1.0/print", methods=['GET'])
def getMethod():  
    return json.dumps({"status": 200, "comment": "[ Get Method ] Hello World"})

# *****************************************************************************************
# Update PUT http://127.0.0.1:5000/api/v1.0/print
# *****************************************************************************************
@app.route("/api/v1.0/print", methods=['PUT'])
def putMethod():  
    return json.dumps({"status": 200, "comment": "[ PUT Method ] Hello World"})

# *****************************************************************************************
# Delete DELETE http://127.0.0.1:5000/api/v1.0/print
# *****************************************************************************************
@app.route("/api/v1.0/print", methods=['DELETE'])
def deleteMethod():  
    return json.dumps({"status": 200, "comment": "[ DELETE Method ] Hello World"})

if __name__ == '__main__':  
    #app.debug = True
    print "inet_addr: " + inet_addr
    app.run(
        host = inet_addr,
        port = 5000
    )

pip install flask  
python crud.py  

  • ngrok
./ngrok http 5000

  • 測試
將上步驟執行後所得到的 Forwarding 網址跟 Python Flask 中所寫的 API 結合
例如: http://c9b990b6.ngrok.io/api/v1.0/print


Ref
GitHub
List of blogs

Archer

Having being a full stack engineer. Experience with C, Python, Go, Swift, JavaScript, Node.js, LinkIt 7697, LinkIt Smart 7688, Raspberry Pi, ARM mbed, IoT solutions. Contact us : [email protected]

ALL RIGHTS RESERVED. COPYRIGHT © 2016. Designed and Coded by Makee.io