问题描述:

I have an MVC Web Api and I can add new record with below request with "simple REST Client"

URL: http://localhost:4585/api/users

Headers: Content-Type: application/json; charset=utf-8

Data:

[{

"username": "name1",

"email": "mail1",

"password": "password1"

},

{

"username": "name2",

"email": "mail2",

"password": "password2"

}]

What I want is doing same thing with python. I've tried below code but the API processed only first record properly.

import json

import urllib2

data = [{ "username": "name1", "email": "mail1", "password": "password1" }, { "username": "name2", "email": "mail2", "password": "password2" }]

response = urllib2.urlopen(req, json.dumps(data))

网友答案:

I did it with requests library.

import requests

requests_session = requests.session()
requests_session.headers.update({'Content-Type': 'application/json'})
requests_session.headers.update({'charset':'utf-8'})

post_data = '[{ "username": "name1", "email": "mail1", "password": "password1" }, { "username": "name2", "email": "mail2", "password": "password2" }]'

requests_response = requests_session.post(url="http://localhost:4585/api/users", data=post_data)

print requests_response.content
相关阅读:
Top