about 4 years ago

將環境建置完成後,再來要試著來處理 GET/POST 連線,

其實沒有真正要做什麼東西,只是想要玩玩看是否真的能成功來 post 資料並且顯示在 web 上,

目標如下:

POST

- 收到 POST 連線後,抓到 post data
- 將 data 內容 output 成一個文字檔
- 回傳收到的 data, time, from ip

GET

- 讀取文字檔內容
- 在 web 上顯示最新的 data 資訊

實作

import flask
import functools
import os
import datetime
import time

app = flask.Flask(__name__)

@app.route('/wtf', methods=['POST', 'GET'])
def wtf():
    fileName = 'lastReceive.txt'


    if flask.request.method == 'GET':
        getFile = open(fileName, 'r')
        text = getFile.read()
        getFile.close()
        spilt = text.split('$')
        return '<br>' + 'Last Received POST Data is : "' + spilt[0] + '"' + '<br>' + 'From : ' + spilt[1]+ '<br>' + 'Date : ' + spilt[2]

    elif flask.request.method == 'POST':

        receivePost = flask.request.stream.read()
        ip = flask.request.remote_addr
        now = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
        write = receivePost + '$' + ip + '$' + now

        if not os.path.isfile(fileName):
            tempFile = open(fileName, 'a')
        else: 
            tempFile = open(fileName, 'w')
        tempFile.write(write)
        tempFile.close()

        return '<br>' + 'Receive POST Data is : "' + receivePost + '"' + '<br>' + 'From : ' + ip + '<br>' + 'Date : ' + now


def main():
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

if __name__ == '__main__': main()
← 雲端平台服務:Heroku ( 建置 python 環境篇 ) 雲端平台服務:Heroku ( 建置 python 環境篇 ) →