Python get and post requests

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_45523154/article/details/102672555

1. The jsonmodule provides a very simple way to encode and decode data JSON. Two of the main functions are json.dumps()and json.loads(), other than the serialization library as much less pickle interface. The following shows how to convert a Python data structures to JSON:


import json

data = {
    'name' : 'ACME',
    'shares' : 100,
    'price' : 542.23
}

json_str = json.dumps(data)

The following shows how to convert a JSON encoded string back to a Python data structure:

data = json.loads(json_str)

2. Simple get and post requests, use import requests


在学习过程中有什么不懂得可以加我的
python学习交流扣扣qun,784758214
群里有不错的学习视频教程、开发工具与电子书籍。
与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容

import requests

response = requests.get('http://httpbin.org/get')
print(response.text)

#通过在发送post请求时添加一个data参数,这个data参数可以通过字典构造成
import requests

data = {
    "name":"zhaofan",
    "age":23
}
response = requests.post("http://httpbin.org/post",data=data)
print(response.text)

3.GET method, and a custom header

# -* - coding: UTF-8 -* - 
import urllib2

request = urllib2.Request("http://www.baidu.com/")
request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
response = urllib2.urlopen(request)
print response.getcode()
print response.geturl()
print response.read()

POST method, and a custom header

# -* - coding: UTF-8 -* - 
import urllib2
import urllib

request = urllib2.Request("http://passport.cnblogs.com/login.aspx")
request.add_header('content-TYPE', 'application/x-www-form-urlencoded')
data={"tbUserName":"test_username", "tbPassword":"test_password"}

response = urllib2.urlopen(request, urllib.urlencode(data))
print response.getcode()
print response.geturl()
print response.read() 

4. The actual test scripting

# coding:utf-8
import json
import urllib2
import requests

class AddScores:
    def __init__(self):
        pass

    def getToken(self):  # 获取token值
        url1 = 'xxxxx'#url
        r1 = requests.get(url1)
        self.tokenObj = json.loads(r1.text)#解码JSON数据

        if self.tokenObj["result"] == "success":
            print self.tokenObj["token"]
        else:
            print "failed"
        return self.tokenObj["token"]

    def personMess(self):  # 获取个人信息
        url2 = 'xxx' + self.getToken()
        r2 = requests.post(url2)
        print r2.text

    def addSco(self,resId):  # 添加分数
        data = {
            "memberId": "xxx",
            "orgCode": "xxx",
            "resourceId": resId,#传参,传resourceId
            "configName": "wsp", "resourceType": "wsp"
        }

        print "添加分数的请求参数:"
        print json.dumps(data)#编码JSON

        headers = {'Content-Type': 'application/json'}
        url3 = 'xxx' + self.getToken()
        re3 = urllib2.Request(url=url3, headers=headers, data=json.dumps(data))
        response = urllib2.urlopen(re3)
        print response.read()

Interested in Python or are studying a small partner, you can join us to learn Python buckle qun: 784758214, look at how seniors are learning! From basic web development python script to, reptiles, django, data mining and other projects to combat zero-based data are finishing. Given to every little python partner! Every day, Daniel explain the timing Python technology, to share some of the ways to learn and need to pay attention to small details, click on Join us python learner gathering

5. TXT file read and write

#coding:utf-8
import time

from Demo2.token import AddScores

class ResId:
    def getResId(self):
        file=open('xxxx')
        # a=file.read()
        # print a
        lId= file.readline()
        lId=lId.strip(',\n')

        while lId != '':#逐行读取数据
            print lId
            addScores = AddScores()
            addScores.getToken()
            addScores.personMess()
            addScores.addSco(lId)

            time.sleep(68)

            lId = file.readline()
            print "============================="

ResId().getResId()

Guess you like

Origin blog.csdn.net/weixin_45523154/article/details/102672555