Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to upload excel data stream with python requests

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use python requests to upload excel data stream", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to upload excel data stream with python requests.

Requests upload excel data stream headers=self.headers # get import template file_home = self.import_template log.info (file_home) wb = load_workbook (filename=file_home) ws = wb ['sheet1'] # modify the name of the waste unit And remarks ws ['b3'] =' itest waste unit'+ self.dic ["t"] ws ['s3'] =' I raw material sales'+ self.dic ["t"] wb.save (file_home) url=self.url_1+ "/ companies/import?companyType=2" payload= {} m=MultipartEncoder (fields= {"parent_dir":'/' "name": 'file', "filename":' name.xlsx', 'file': (' name.xlsx',open (file_home,'rb'), 'application/vnd.ms-excel')}) headers [' Content-Type'] = m.content_type r=requests.post (url,headers=headers) Data=m) log.info (r.json ()) data driven python+requests+excel data driven

It is tested according to the data, such as reading the test cases in the excel table and automatically filling in the test results. Sending the test report includes the following modules:

1. Get use cases

two。 Call interface

3. Check result

4. Send test report

5. Exception handling

6. Log module

1. First of all, design the test case

two。 Establish a file structure

The automated testing framework is named as: writing the main program in the ATP,bin directory, test cases in the cases directory, configuration files in the conf directory, encapsulated modules in the lib directory, log files in the logs directory, and readme files.

3. Encapsulation module

Common.py: encapsulates the modules of reading excel use cases, calling interfaces, verifying results, and writing reports.

Step 1: read the use case in excel step 2: send the request according to the use case step 3: verify the result step 4: write the test result and return message to excel "" import xlrd,requestsfrom xlutils import copyfrom lib.log import atp_logclass OpCase (object): def get_case (self) File_path): cases= [] # defines a list of all cases if file_path.endswith ('.xls') or file_path.endswith ('.xlsx'): try: book = xlrd.open_workbook (file_path) sheet = book.sheet_by_index (0) for i in range (1) Sheet.nrows): row_data = sheet.row_values (I) # every row of data obtained is saved in the list row_data cases.append (row_data [4:8]) atp_log.info ('read% s use cases'% (len (cases) self.file_path = file_path # because the function has passed the parameter path To facilitate write_excel reference, instantiate except Exception as e: atp_log.error ('[% s] use case acquisition failed, error message:%% file_path,e) else: atp_log.error ('illegal use case file) % s'%file_path) return cases def my_request (self,url,method,data): data = self.dataToDict (data) try: if method.upper () = 'POST': res = requests.post (url,data). Text elif method.uper () =' GET': res = requests.get (url) Params=data) .text else: atp_log.warning ('this request method is not supported temporarily') res = 'this request method is not supported for the time being' except Exception as e: msg ='[% s] API call failed %% (url,e) atp_log.error (msg) res = msg return res def dataToDict (self,data): # convert the data into a dictionary Res = {} data = data.split (',') for d in data: # k, v = d.split ('=') res [k] = v def check_res (self,res,check): # res: actual result Check: expected result res = res.replace ('":','='). Replace ('":','=') for c in check.split (','): if c not in res: atp_log.info ('result check failed, expected result: [% s] Actual result [% s]'% (cje res)) return 'failed' return 'successful' def write_excel (self Case_res): book = xlrd.open_workbook (self.file_path) new_book = copy.copy (book) sheet = new_book.get_sheet (0) row = 1 for case_case in case_res: sheet.write (row,8,case_case [0]) sheet.write (row,9 Case_case [1]) row + = 1 new_book.save (self.file_path.replace ('xlsx','xls'))

Log.py: encapsulates the log module

Import logging,osfrom logging import handlersfrom conf import settingclass Mylogger (): def _ _ init__ (self,file_name,level='info',backCount=5,when='D'): logger = logging.getLogger () # instantiate a logger object first First create an office logger.setLevel (self.get_level (level)) # set the level of the log # F1 = logging.FileHandler (filename='a.log',mode='a',encoding='utf-8') # find the person who wrote the log file C1 = logging.StreamHandler () # responsible for outputting b1 = handlers.TimedRotatingFileHandler (filename=file_name, when=when, interval=1, backupCount=backCount) to the console Encoding='utf-8') fmt = logging.Formatter ('% (asctime) s -% (pathname) s [line:% (lineno) d] -% (levelname) s:% (message) s') c1.setFormatter (fmt) b1.setFormatter (fmt) logger.addHandler (C1) logger.addHandler (b1) self.logger = logger def get_level (self) Str): level = {'debug':logging.DEBUG,' info':logging.INFO, 'warm':logging.WARNING,' error':logging.ERROR} str = str.lower () return level.get (str) path = os.path.join (setting.LOG_PATH,setting.LOG_NAME) atp_log = Mylogger (path 'debug') .logger # is instantiated directly here When you use it, you don't have to instantiate it. # when you use it elsewhere, just atp_log.warnning ('xxxx').

Send_mail.py: encapsulates the module of sending mail

Import yagmailfrom conf import settingfrom lib.log import atp_logdef sendmail (title,content,attrs=None): M = yagmail.SMTP (host=setting.MAIL_HOST,user=setting.MAIL_USER, password=setting.MAIL_PASSWRD,smtp_ssl=True) m.send (to=setting.TO, subject=title, contents = content, attachments = attrs) atp_log.info ('send email completed') 4. Configuration file

Setting.py, profile: set email address, log default level, use case storage path, log storage path, log file name

Import osBASE_PATH = os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__) # navigate to the ATP directory in the three-tier directory MAIL_HOST = 'smtp.qq.com'MAIL_USER='12*89@qq.com'MAIL_PASSWRD =' gjn*bcgh'TO = ['129roomqq.com'] LEVEL = 'debug' # set the default level of the log LOG_PATH = os.path.join (BASE_PATH 'logs') # log file in the logs directory CASE_PATH = os.path.join (BASE_PATH,'cases') # use case file in the cases directory LOG_NAME =' log # sets the log file name 5. Change the ATP file

Mark directory as Sources Root

6. Write the main program

Start.py

Import os,sysBASE_PATH = os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__) sys.path.insert (0 BASE_PATH) from lib.common import OpCasefrom lib.send_mail import sendmailfrom conf import settingclass CaseRun (object): def find_case (self): op = OpCase () for fin os.listdir (setting.CASE_PATH): # read an excel abs_path = os.path.join (setting.CASE_PATH) per loop F) case_list = op.get_case (abs_path) res_list = [] pass_count,fail_count= 0 for case in case_list: # all use cases in each excel loop url,method,req_data,check = case res = op.my_request (url,method Req_data) # the result returned after calling the API status = op.check_res (res,check) res_list.append ([res) Status]) if status = 'pass': pass_count + = 1 else: fail_count + = 1 op.write_excel (res_list) msg ='xx Hello This time, a total of% s use cases were run, through% s, failed% s. ''% (len (res_list), pass_count,fail_count) sendmail ('test case run results', content=msg,attrs=abs_path) CaseRun () .find_case ()

OK, write the data-driven automated test framework, run the start.py program, and receive the following message:

At this point, I believe you have a deeper understanding of "how to upload excel data streams with python requests". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report