文章标题

    xiaoxiao2021-03-26  25

    ***python assert* 对那些没有意识到用断言的最佳时机的人来说,Python的断言就是检测一个条件,如果条件为真,它什么都不做;反之它触发一个带可选错误信息的AssertionError eg:>>> mylist = [‘item’]

    assert len(mylist) >= 1 mylist.pop() assert len(mylist) >= 1 Traceback (most recent call last): File “”, line 1, in **AssertionErro**r eg:py> x = 23 py> assert x > 0, “x is not zero or negative” py> assert x%2 == 0**, “x is not an even number”** Traceback (most recent call last): File “”, line 1, in AssertionError: x is not an even number

    python 接口测试 1.没有basicauthentication get: import urllib2 response=urllib2.urlopen(url) print response.read() post: import urllib import urllib2 post_data=urllib.encode({key:value}) responese=urllib2.urlopen(url.post_data) print response.read() print response.getheaders()

    ….. urllib.urlencode()

    不幸的是,这个函数只能接收key-value pair格式的数据。即只针对dict的, 并且目前不提供urldecode方法

    import urllib params = urllib.urlencode({‘spam’: 1, ‘eggs’: 2, ‘bacon’: 0})

    params = urllib.urlencode({‘spam’: 1, ‘eggs’: 2, ‘bacon’: 0}) params ###自动转化成下面url的参数形式 ‘eggs=2&bacon=0&spam=1’

    f = urllib.urlopen(“http://www.musi-cal.com/cgi-bin/query?%s” % params) print f.read() …….

    2有basicauthentication get: import urllib2 response=urllib2.urlopen(url) print response.read()

    post: 方法一

    创建密码管理器

    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

    添加用户名和密码.

    如果知道realm,用它代替None.

    top_level_url = “http://www.163.com/” password_mgr.add_password(None, top_level_url, username, password) handler = urllib2.HTTPBasicAuthHandler(password_mgr)

    创建opener

    opener = urllib2.build_opener(handler)

    打开一个url

    opener.open(a_url)

    安装opener,以后urllib2.urlopen都会用它。

    urllib2.install_opener(opener)

    方法二 requests import requests get: print requests.get(url).text post: r=requests.post(url,data={},auth=(‘username’,’password’)) print r.status_code print r.headers print r.reason

    转载请注明原文地址: https://ju.6miu.com/read-662494.html

    最新回复(0)