import json
import requests
from common.baselogger import logger
class WebRequests(object):
def __init__(self):
pass
@staticmethod
def get(url, params=None, headers=None, files=None):
""" encapsulation get Method ,return Response code and response content """
try:
logger.info("=======================================================")
logger.info("get url:%s" % url)
logger.info(" request header:%s" % headers)
logger.info(" request body:%s" % params)
response = requests.get(url, params=params, headers=headers, files=files)
status_code = response.status_code # Get the returned status code
logger.info(" Get the returned status code :%d" % status_code)
# If the return is not json Format , It doesn't change , Straight back to the content
if '<!DOCTYPE html>' in str(response.content):
logger.info(" Response content :%s" % str(response.content))
return status_code, str(response.content)
else:
response_json = response.json() # Response content ,json Type conversion to python data type
logger.info(" Response content :%s" % response_json)
return status_code, response_json # Return response code , Response content
except BaseException as e:
logger.error(" request was aborted !", exc_info=1)
@staticmethod
def post(url, data=None, headers=None, data_to_json=True):
""" encapsulation post Method , And use json Format value transfer ,return Response code and response content """
try:
logger.info("=======================================================")
logger.info("post url:%s" % url)
logger.info(" request header:%s" % headers)
logger.info(" request body:%s" % data)
if data_to_json:
data = json.dumps(data).encode('utf-8') # python Data types are converted to json data type
response = requests.post(url, data=data, headers=headers)
status_code = response.status_code # Get the returned status code
logger.info(" Get the returned status code :%d" % status_code)
response_json = response.json() # Response content ,json Type conversion to python data type
logger.info(" Response content :%s" % response_json)
return status_code, response_json # Return response code , Response content
except BaseException as e:
logger.error(" request was aborted !", exc_info=1)
@staticmethod
def put(url, data=None, headers=None):
""" encapsulation put Method , If it contains “{” Then use json Format value transfer , Otherwise, direct transmission ,return Response code and response content """
try:
logger.info("=======================================================")
logger.info("put url:%s" % url)
logger.info(" request header:%s" % headers)
logger.info(" request body:%s" % data)
if '{' in data and '}' in data:
data = json.dumps(data).encode('utf-8') # python Data types are converted to json data type
response = requests.put(url, data=data, headers=headers)
status_code = response.status_code # Get the returned status code
logger.info(" Get the returned status code :%d" % status_code)
response_json = response.json() # Response content ,json Type conversion to python data type
logger.info(" Response content :%s" % response_json)
return status_code, response_json # Return response code , Response content
except BaseException as e:
logger.error(" request was aborted !", exc_info=1)
@staticmethod
def delete(url, data=None, headers=None):
""" encapsulation delete Method , And use json Format value transfer ,return Response code and response content """
try:
logger.info("=======================================================")
logger.info("delete url:%s" % url)
logger.info(" request header:%s" % headers)
logger.info(" request body:%s" % data)
data = json.dumps(data).encode('utf-8') # python Data types are converted to json data type
response = requests.delete(url, data=data, headers=headers)
status_code = response.status_code # Get the returned status code
logger.info(" Get the returned status code :%d" % status_code)
response_json = response.json() # Response content ,json Type conversion to python data type
logger.info(" Response content :%s" % response_json)
return status_code, response_json # Return response code , Response content
except BaseException as e:
logger.error(" request was aborted !", exc_info=1)
if __name__ == '__main__':
url = 'https://www.sojson.com/open/api/weather/json.shtml'
payload = {'city': ' Shanghai '}
WebRequests.get(url, payload)
post Submitted multipart/form-data; boundary=
def upload_image_to_file(token, image, expected_code):
""" Edit page to upload pictures """
raw_url = "{test_env}{api_path}".format(test_env=UrlData.TestEnv.value, api_path=UrlData.UploadToFile.value)
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundaryDzEFEPtsX8NXD1sL",
'cache-control': "no-cache",
'Authorization': token,
}
filename = os.path.basename(image)
multipart_encoder = MultipartEncoder(
fields={ # Here, you can set the parameter format as required
'file': (filename, open(image, 'rb'), 'image/jpeg'),
'Content-Type': 'application/octet-stream',
'Content-Disposition': 'form-data;name="file";filename="{0}"'.format(filename),
})
headers['Content-Type'] = multipart_encoder.content_type
# The request header must contain Content-Type: multipart/form-data; boundary=${bound}
# You can also customize boundary
# response = requests.post(raw_url, data=multipart_encoder, headers=headers)
status_code, resp_body = WebRequests.post(raw_url, data=multipart_encoder, headers=headers, data_to_json=False)
assert_equal(status_code, expected_code)
return resp_body