1. 程式人生 > 實用技巧 >Flask常用方法函式彙總

Flask常用方法函式彙總

客服端:

#!/usr/bin/env python
# encoding: utf-8
import requests
import json,time

def post_results(Download_link,Time):
    params = {
        'download_link':Download_link,
        'time':Time
    }
    print(params)
    r = requests.post('http://127.0.0.1:8000/subcontract',  params=params)
    json_obj = json.loads(r.text)
    
print(json_obj) def get_results(Download_link,Time): params = { 'download_link':Download_link, 'time':Time } print(params) r = requests.get('http://127.0.0.1:8000/subcontract', params=params) json_obj = json.loads(r.text) print(json_obj) if __name__ == '__main__'
: _time=int(time.time()) post_results('http://pkg.superdalan.com/game.pkg/download?pkgId=2990&f=chwyqmdmxttiOS_dalan_xy_dsdk_74_1.0.0_20200710_134530.apk',_time) get_results('http://pkg.superdalan.com/game.pkg/download?pkgId=2990&f=chwyqmdmxttiOS_dalan_xy_dsdk_74_1.0.0_20200710_134530.apk',_time)

服務端:

#!/usr/bin/env python
# encoding: utf-8
import flask,json
from flask import request, jsonify  # 想獲取到請求引數的話,就得用這個

server = flask.Flask(__name__)  # 把這個python檔案當做一個web服務

# 響應
def respond(flag, code, _method,msg=''):
    ret = {
        'code': code,
        'status': flag,
        'msg': msg,
        'method':_method
    }
    server.logger.info(ret)#日誌記錄響應結果
    return jsonify(ret)


@server.route('/subcontract', methods=['post','get'])  # 介面的路徑
def add_subcontract():
    print('獲取請求頭',request.headers)#獲取請求headers
    print('獲取請求方式',request.method)
    print('獲取請求cookes',request.cookies)
    print(request.headers.get("User-Agent"))##獲取頭部資訊中User-Agent資訊
    print('獲取URL',request.url)#包含主機+介面名稱
    print('獲取介面名稱',request.path)
    print('獲取服務端ip:埠',request.url_root)

    if request.method=='POST':
         ##通過json提交
        if bool((request.args).to_dict()):
            print('獲取json全部請求引數:',request.args)#獲取json請求引數
            print('json請求引數轉字典:',(request.args).to_dict())
            print('獲取指定引數的值',request.values.get('time'))#獲取指定的請求引數值
            print('獲取json指定key的值',request.args['download_link'])
            print('指定請求引數',request.args.get("time"))
        ##普通的key/value的形式以表單form提交
        elif bool((request.form).to_dict()):
            print('指定請求引數',request.values.get('time'))
            print('指定請求引數',request.form.get('time'))
            print('獲取表單全部請求引數',request.form)
            print('獲取表單全部請求引數轉字典',(request.form).to_dict())
            print('獲取表單全部請求引數轉字典',request.values.to_dict())
        return respond(True, 200, 'POST',msg="渠道包上傳成功!")

    elif request.method=='GET':
        print('獲取get全部引數',request.args)
        print('獲取get請求引數轉字典',request.args.to_dict())
        print('獲取get全部引數',request.args.get('download_link'))

        '''
        request.args.get("key") 獲取get請求引數
        request.values.get("key") 獲取所有引數
        '''
        return respond(True, 200, 'GET',msg="渠道包上傳成功!")



if __name__ == '__main__':
    server.run(port=8000, debug=True, host='0.0.0.0')