1. 程式人生 > >前-後端的一點小理解

前-後端的一點小理解

寫一點自己對前後端的理解

剛開始搜尋後端框架,全部是基於web後端的,我心裡就在想,這什麼玩意,自己也玩過django,沒發現這玩意還有這麼多功能啊

話不多逼逼,貼上自己對這個實驗的理解:

1.首先定義客戶機與伺服器,這裡用自己的電腦的不同埠來模擬客戶機與伺服器,5001埠為客戶機

if __name__ == '__main__':
    app.run(port=5001, debug=True)

5000埠為伺服器(run函式預設啟動為5000埠),埠之間相互收發資料即可模擬為客戶機與伺服器通訊(這裡忽略網路延遲)

if __name__ == '__main__':
    app.run(debug
=True)

2.客戶端傳送圖片給伺服器,此時要理解url,是個很重要的東西,客戶機與伺服器相互之間選擇不同的服務,即靠不同的url來觸發,比如:客戶機需要向伺服器傳送圖片,那麼客戶機首先需要把圖片放入request物件中,再把該request物件發往5000埠,且url為uploads(以下為客戶端的程式碼)

import requests

files = {'image01': open('images/giraffe.jpg', 'rb')}
user_info = {'name': 'panli'}
r = requests.post("http://127.0.0.1:5000/upload", data=user_info, files
=files) print(r.text)

3.此時,伺服器會不斷監聽5000埠,在收到request請求後,根據request中的url去觸發服務端對應的服務函式,在這裡,url為uploads對應的響應函式為upload,upload功能為接收request物件,取出其中的圖片,儲存並跑影象識別演算法,再呼叫結果返回函式,把識別結果返回給客戶端(以下為服務端的程式碼)

@app.route('/upload', methods=['POST'])
def upload():
    upload_file = request.files['image01']
    if upload_file and
allowed_file(upload_file.filename): filename = secure_filename(upload_file.filename) upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename)) os.system("python ./test_yolo.py model_data/yolo.h5") returnjpg.return_jpg() return 'hello, ' + request.form.get('name', 'little apple') + '. success' else: return 'hello, ' + request.form.get('name', 'little apple') + '. failed'

4.傳送識別結果給客戶端的程式碼如下,注意這裡的埠為5001,即為客戶端的埠號,url為receive(以下為服務端程式碼)

import requests

def return_jpg():
    files = {'image01': open('images/out/giraffe.jpg', 'rb')}
    user_info = {'name': 'panli'}
    r = requests.post("http://127.0.0.1:5001/receive", data=user_info, files=files)
    print(r.text)

5.客戶端監聽5001埠,收到request請求後,檢視url為receive,即觸發對應的響應函式,儲存識別結果,完工

@app.route('/receive', methods=['POST'])
def upload():
    upload_file = request.files['image01']
    if upload_file and allowed_file(upload_file.filename):
        filename = secure_filename(upload_file.filename)
        upload_file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
        return 'hello, ' + request.form.get('name', 'little apple') + '. success'
    else:
        return 'hello, ' + request.form.get('name', 'little apple') + '. failed'

覺得自己就是個sb,這麼簡單的功能都搞了幾天???順便,後端框架為flask