使用Python请求发布JSON

时间:2012-03-16 07:46:50

标签: python json python-requests cherrypy

我需要将JSON从客户端发送到服务器。我正在使用Python 2.7.1和simplejson。客户端正在使用请求。服务器是CherryPy。我可以从服务器获取硬编码的JSON(代码未显示),但是当我尝试将JSON发布到服务器时,我收到“400 Bad Request”。

这是我的客户代码:

data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
data_json = simplejson.dumps(data)
payload = {'json_payload': data_json}
r = requests.post("http://localhost:8080", data=payload)

这是服务器代码。

class Root(object):

    def __init__(self, content):
        self.content = content
        print self.content  # this works

    exposed = True

    def GET(self):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(self.content)

    def POST(self):
        self.content = simplejson.loads(cherrypy.request.body.read())

有什么想法吗?

8 个答案:

答案 0 :(得分:735)

从请求版本2.4.2及更高版本开始,您可以在调用中使用'json'参数,这样可以更简单。

>>> import requests
>>> r = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> r.status_code
200
>>> r.json()
{'args': {},
 'data': '{"key": "value"}',
 'files': {},
 'form': {},
 'headers': {'Accept': '*/*',
             'Accept-Encoding': 'gzip, deflate',
             'Connection': 'close',
             'Content-Length': '16',
             'Content-Type': 'application/json',
             'Host': 'httpbin.org',
             'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
             'X-Request-Id': 'xx-xx-xx'},
 'json': {'key': 'value'},
 'origin': 'x.x.x.x',
 'url': 'http://httpbin.org/post'}

编辑:此功能已添加到官方文档中。您可以在此处查看:Requests documentation

答案 1 :(得分:314)

事实证明我错过了标题信息。以下作品:

url = "http://localhost:8080"
data = {'sender': 'Alice', 'receiver': 'Bob', 'message': 'We did it!'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

答案 2 :(得分:51)

根据请求2.4.2(https://pypi.python.org/pypi/requests)," json"参数受支持。无需指定" Content-Type"。所以较短的版本:

requests.post('http://httpbin.org/post', json={'test': 'cheers'})

答案 3 :(得分:16)

更好的方法是:

url = "http://xxx.xxxx.xx"

datas = {"cardno":"6248889874650987","systemIdentify":"s08","sourceChannel": 12}

headers = {'Content-type': 'application/json'}

rsp = requests.post(url, json=datas, headers=headers)

答案 4 :(得分:11)

(数据/ json /文件)之间应使用哪个参数,它实际上取决于名为ContentType的请求标头(通常通过浏览器的开发人员工具进行检查),

当Content-Type为application / x-www-form-urlencoded时, 代码应为:

requests.post(url, data=jsonObj)

当Content-Type为application / json时, 您的代码应该是以下之一:

requests.post(url, json=jsonObj)
requests.post(url, data=jsonstr, headers={"Content-Type":"application/json"})

当Content-Type为multipart / form-data时,它用于上传文件, 因此您的代码应为:

requests.post(url, files=xxxx)

答案 5 :(得分:0)

与python 3.5 +完美配合

客户端:

import requests
data = {'sender':   'Alice',
    'receiver': 'Bob',
    'message':  'We did it!'}
r = requests.post("http://localhost:8080", json={'json_payload': data})

服务器:

class Root(object):

    def __init__(self, content):
        self.content = content
        print self.content  # this works

    exposed = True

    def GET(self):
        cherrypy.response.headers['Content-Type'] = 'application/json'
        return simplejson.dumps(self.content)

    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def POST(self):
        self.content = cherrypy.request.json
        return {'status': 'success', 'message': 'updated'}

答案 6 :(得分:-1)

始终建议我们需要具备读取 JSON 文件并将对象解析为请求正文的能力。我们不会解析请求中的原始数据,因此以下方法将帮助您解决。

def POST_request():
    with open("FILE PATH", "r") as data:
        JSON_Body = data.read()
    response = requests.post(url="URL", data=JSON_Body)
    assert response.status_code == 200

答案 7 :(得分:-3)

这适用于Python版本3.5, 如果URL包含查询字符串/参数值,

请求网址= https://baaaah2.com/ws/rest/v1/concept/

参数值= 21f6bb43-98a1-419d-8f0c-8133669e40ca

var express = require('express');
var router = express.Router();
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;
var crypto = require('crypto');

var User = require('../models/user');
var sqlite3 = require('sqlite3');

var db = new sqlite3.Database('./database.sqlite3');

//Register
router.get('/register', function(req,res) {
res.render('register');

});

 //Login
router.get('/login', function(req,res) {
res.render('login');

});

//Register User
router.post('/register', function(req,res) {
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;


//Validation 
req.checkBody('username', 'Username is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('password', 'Password is required').notEmpty();
req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

var errors = req.validationErrors();

if (errors){
    res.render('register', {
        errors:errors
    });

} else {
    var stmt = db.prepare("INSERT INTO users ( id, username, email, password, salt ) VALUES (NULL, ?, ?, ?, ?)");
                stmt.run([ username, email, password[0], 'string' ]).finalize();
    // GIVE ME A FLASH MESSAGE AND REDIRECT TO LOGIN
    req.flash('success_msg','You are registered and can now login');
    res.redirect('/users/login');

}
});
// LOGIN

function hashPassword(password, salt) {
  var hash = crypto.createHash('sha256');
  hash.update(password);
  hash.update(salt);
  return hash.digest('hex');
}

   passport.use(new LocalStrategy(function(username, password, done) {
  db.get('SELECT * FROM users WHERE username = ?', username,     function(err, row) {
if (!row) return done(null, false,{message: 'Unknown User'});
var hash = hashPassword(password, row.salt);
  db.get('SELECT * FROM users WHERE username = ? AND password = ?',     username, hash, function(err, row) {
  if (!row) return done(null, false,{message: 'Invalid password'});
  return done(null, row);
});
  });
    }));


// SERIALIZE AND DESERIALIZE USER
passport.serializeUser(function(user, done) {
      return done(null, user.id);
    });

passport.deserializeUser(function(id, done) {
db.get('SELECT id, username FROM users WHERE id = ?', id, function(err, row) {
if (!row) return done(null, false);
return done(null, row);
  });
});


router.post('/login', passport.authenticate('local', { successRedirect: '/',

                                                failureRedirect: '/users/login',failureFlash:true }),
function(req,res) {
res.redirect('/');
});

router.get('/logout',function(req,res){
req.logout();

req.flash('success_msg','You are logged out');

res.redirect('/users/login');
})


module.exports = router;