Related use of Python requests Library

Keywords: JSON Python Spring Mybatis

Related use of requests Library

More dry cargo

Use

install

pip install requests

Verify whether the installation is successful: whether python client import requests report errors. If there is no error, it indicates success

Example 1

  • Using requests to request post to get the return data
import requests
import json

data = {
	'username':'nick',
	'password':'123'
}

url = "http://localhost:8000/login/"

res = requests.post(url=url, data=data)

print (type(res.json()))
print (res.json())
  • Further grouping of post and get requests
import requests
import json


def send_post(url, data):
	res = requests.post(url=url, data=data).json()
	return json.dumps(res, indent=2, sort_keys=True)


def send_get(url,data):
	res = requests.get(url=url,data=data).json()
	return json.dumps(res, indent=2, sort_keys=True)

def run_main(url,method,data=None):
	res = None
	if method == 'GET':
		res = send_get(url,data)
	else:
		res = send_post(url,data)
	return res

data = {
	'username':'nick',
	'password':'123'
}

url = "http://localhost:8000/login/"
run_main(url, "POST", data)

print(run_main(url, "POST", data))


  • Encapsulate it as a class
import requests
import json

class RunMain:	

	def __init__(self, url, method, data=None):
		self.res = self.run_main(url, method, data)

	def send_post(self, url, data):
		res = requests.post(url=url, data=data).json()
		return json.dumps(res, indent=2, sort_keys=True)


	def send_get(self, url, data):
		res = requests.get(url=url,data=data).json()
		return json.dumps(res, indent=2, sort_keys=True)

	def run_main(self, url, method, data=None):
		res = None
		if method == 'GET':
			res = self.send_get(url,data)
		else:
			res = self.send_post(url,data)
		return res

if __name__ == '__main__':

	data = {
		'username':'nick',
		'password':'123'
	}

	url = "http://localhost:8000/login/"
	run = RunMain(url, "POST", data)
	print(run.res)

Other

View python installation path

notepad tip how to add the same string before and after multiple lines at the same time

ctrl + alt and down. Multiple lines will be selected

Posted by aron on Tue, 31 Mar 2020 10:35:58 -0700