用Python 實現一個簡單的postman功能
阿新 • • 發佈:2019-01-10
用Python 實現一個簡單的postman功能
import os import requests import json import defaultdict as default_dict class PostMan: __instance = None def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls, *args) return cls.__instance def postMan(self, data): return json.dumps(data, indent=4, ensure_ascii=False) class GetInfo: def __init__(self): self.url = 'your url' def get_test_info(self, params): headers = {'content-type': 'application/json'} payload = json.dumps(params) res = requests.post(self.url, data=payload, headers=headers).json() post = PostMan() print post.postMan(res) class operation: def get_file_text(self, filename, params): ''' 獲取檔名稱,並輸出數資料 :param filename: :return: ''' file = 'post_file/{0}.txt'.format(filename) list_file = 'post_file/list.txt' exist_list = self.read_list(list_file) if params: with open(list_file, 'a+') as f, open(file, 'w') as fs: if filename not in exist_list: f.write(filename + '\n') fs.write(params) return self.read(file) def read(self, file): ''' :param file: :return: ''' final = default_dict() with open(file, 'r') as f: result = f.readlines() for r in result: strip_op = r.strip('/\n') num = strip_op.find(':') if num > 0 and '#' not in strip_op: final[strip_op[:num]] = strip_op[num + 1:] return final def read_list(self, list_file): ''' 讀取list檔案 :param list_file: :return: ''' new_list = [] with open(list_file, 'r') as f: result = f.readlines() for res in result: res = res.strip('/\n') if '#' not in res: new_list.append(res) return new_list def main(params=None): ''' :param filename: :return: ''' filename = 'function_code' op = operation() params = op.get_file_text(filename, params) info = GetInfo() info.get_test_info(params) #這個裡面寫入要傳入的欄位 params = ''' id:78949465 name:奧巴馬 ''' if __name__ == '__main__': main(params)