浅谈python3发送post请求参数为空的情况

yipeiwu_com6年前Python基础

post请求的时候如果不带参数,其实作用就跟get请求一样。我们在做接口测试的时候,发现开发就全部使用的post,get的作用就被这样的post空参数请求给替代了。

在Python代码请求,如下:

class HttpHelper():
 
 def __init__(self):
  '''获取driver对象,和接口ip地址信息,里面的方法大家可以忽略,根据自己的情况来设置
  '''
  self.dr=Common.driver
  run_info=Common().get_current_run_config()
  app_info=Common().get_app_config()[run_info['_envir']]
  self.ip=app_info['url'].split('/')[2]
 
 def post(self,module,interface_name,post_para={}):
  '''arg: module 模块名
    interface_name 接口名称
    post_para  请求参数,默认是空字典,如果不填这个参数就是post请求参数为空的情况
  '''
  inter_info=Common().get_interface_info()[module]
  url='http://'+self.ip+inter_info[interface_name]['url']
  Common().logger_info("request - api - "+url)
  
  postdata = bytes(urllib.parse.urlencode(post_para), encoding='utf8') 
  Common().logger_info("request - arg - "+str(post_para))
  _jid=Common().get_jsessionid(self.dr) #获取sessionid,这个方法是通过selenium的get_cookie方法来获取sessionid,大家可以参考我其他的文章
  header={
   'Accept':'application/json, text/plain, */*',
   'Connection': 'keep-alive',
   'Content-Type':'application/x-www-form-urlencoded',
   'Cookie':'JSESSIONID='+_jid+'',
   'Host': ''+self.ip+'',
   'Origin': 'http://'+self.ip+''
   }
  Common().logger_info("[header] - "+str(header))
  try:
   req=urllib.request.Request(url,postdata,header)
   with urllib.request.urlopen(req) as resp:
    response=resp.read().decode('utf-8')
    response=json.loads(response)
    Common().logger_info('response - '+str(response))
    if response['data']!='':
     Common().logger_info('http post success!!!')
    return response
  except Exception as e:
   Common().logger_error(str(e))

代码里的Common().logger_***是我们项目的日志方法,输出一些执行日志,大家可以忽略。

以上这篇浅谈python3发送post请求参数为空的情况就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 实现识别图片上的数字

python 实现识别图片上的数字

Python 3.6 版本 Pytesseract 图像验证码识别 环境: (1) win7 64位 (2) Idea (3) python 3.6 (4) pip install pi...

pytorch 利用lstm做mnist手写数字识别分类的实例

代码如下,U我认为对于新手来说最重要的是学会rnn读取数据的格式。 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 08:53:25...

python按行读取文件,去掉每行的换行符\n的实例

如下所示: for line in file.readlines(): line=line.strip('\n') 以上这篇python按行读取文件,去掉每行的换行符\n的实例就是...

pygame实现俄罗斯方块游戏(对战篇1)

pygame实现俄罗斯方块游戏(对战篇1)

上篇更新到pygame实现俄罗斯方块游戏(AI篇2) ,原本应该继续做优化,不过考虑到完成游戏完整性,这张就先把对战做好。 一、对战的方块管理 定义一个BlockManage管理对战的方...

使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法

使用pandas模块读取csv文件和excel表格,并用matplotlib画图的方法

如下所示: # coding=utf-8 import pandas as pd # 读取csv文件 3列取名为 name,sex,births,后面参数格式为names= name...