Pythonで簡単なpostman機能を実現

2704 ワード

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 + '
') 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('/
') 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('/
') 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)