Create Mime/multipart Request Containing Multiple Http Requests
I am following this tutorial for batching http requests with ASP.NET 4.5. I have the sample working, and now I need to write a client application in Python. This code creates, and
Solution 1:
I've managed to translate the first part of the C# sample into Python using the following code:
classBatchRequest:
'ClassforsendingseveralHTTPrequestsinasinglerequest'
def__init__(self, url, uuid):
self.batch_url = batch_urlself.uuid = uuidself.data = ""
self.headers = {"Content-Type" : "multipart/mixed; boundary=\"batch_{0}\"".format(uuid)}
#Build sub-request depending on Method and Data supplied
def add_request(self, method, url, data={}):
if method =="GET":
self.data +="--batch_{0}\r\nContent-Type: application/http; msgtype=request\r\n\r\n{1} {2} HTTP/1.1\r\nHost: localhost:65200\r\n\r\n\r\n".format(uuid, method, url)
#If no data, have alternative option
elif method =="POST" or method =="PUT":
self.data +="--batch_{0}\r\nContent-Type: application/http; msgtype=request\r\n\r\n{1} {2} HTTP/1.1\r\nHost: localhost:65200\r\nContent-Type: application/json; charset=utf-8\r\n\r\n{3}\r\n".format(uuid, method, url, json.dumps(data))
elif method =="DELETE":
self.data +="--batch_{0}\r\nContent-Type: application/http; msgtype=request\r\n\r\n{1} {2} HTTP/1.1\r\nHost: localhost:65200\r\n\r\n\r\n".format(uuid, method, url)
def execute_request(self):
#Add the "closing" boundary
self.data +="--batch_{0}--\r\n".format(uuid)
result = requests.post(self.batch_url, data=self.data, headers=self.headers)
return result
if __name__ == '__main__':
url ="http://localhost:65200/api"
batch_url ="{0}/batch".format(url)
uuid = uuid.uuid4()
br =BatchRequest("http://localhost:65200/api", uuid)
#Get customers
br.add_request("GET", "/api/Customers")
#Create a new customer
new_customer = {"Id" : 10, "Name" : "Name 10"};
br.add_request("POST", "/api/Customers", new_customer)
#Update the name of the first customer in the list
update_customer = customer_list[0]
update_customer["Name"] ="Peter"
br.add_request("PUT", "/api/Customers/{0}".format(update_customer["Id"]), update_customer)
#Remove the second customer in the list
br.add_request("DELETE", "/api/Customers/{0}".format(customer_list[1]["Id"]))
result = br.execute_request()
All that remains is to figure out how to parse the response(s) from the server.
Post a Comment for "Create Mime/multipart Request Containing Multiple Http Requests"