Python用json请求400错误

时间:2016-05-12 17:02:34

标签: python json

我正在使用以下代码在API端点中注册用户:

import argparse
import requests
import ConfigParser
import json
import sys
import logging
#from collections import OrderedDict
#from cs-check-user.py import get

# Configuration Parameters
env = 'Pre_internal'

Config = ConfigParser.ConfigParser()
Config.read("../etc/config.ini")
endpoint = Config.get(env, 'endpoint')
admin_user = Config.get(env, 'admin_user')
admin_password = Config.get(env, 'admin_password')

# Logging Config
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(name)s %(message)s',
                    filename='../logs/create_user.log')

# Functions
def post(login, email, password):
        login_ok = login.lower()

    #data = OrderedDict([('login',login_ok), 
    #                      ('email', email), 
    #                      ('password', password)])
    #data_ok = json.dumps(data, sort_keys=False)
    #data = '{"login": login, "email": email, "password": password}'
    #create_user = requests.post(endpoint, data, auth=(admin_user, admin_password))

        data = {"login": login_ok, "email": email, "password": password}
        headers = {'Content-Type': 'application/json'}
        create_user = requests.post(endpoint, data=json.dumps(data), headers=headers, auth=(admin_user, admin_password))

    if create_user.status_code == 202:
        print 'User has been created successfully'
        logging.info('User has been created successfully %s', login_ok)
        sys.exit(0)

    else:
        print 'Error Received: ', create_user
        logging.error('Received error when creating the user %s %s', login_ok, create_user)
        sys.exit(1)

# Main
parser = argparse.ArgumentParser( description='''Script to create users in Cloud Storage''', epilog='''Example: ./cs-create-user.py -l dsmc -e dsmc@tid.es -p changeme''' )

parser.add_argument('-l', '--login', help='Login account')
parser.add_argument('-e', '--email', help='Email account')
parser.add_argument('-p', '--password', help='Password account')
args = parser.parse_args()

if not args.login:
        print 'Login incomplete'
if not args.password:
        print 'Password incomplete'
if not args.email:
        print 'Email incomplete'
else:
    # Check user
    #try:
    #   get(args.login)
    #except SystemExit as exc:
    #   if exc.code == 0:
    #       print 'The user already exists, please select another login.'
    #       sys.exit(1)
    #   else:
            post(args.login, args.password, args.email)
    #
    #   post(args.login, args.password, args.email)
sys.exit(0)

三小时后,我不知道为什么我一直收到400!我认为这个问题与json格式有关,但为什么呢?

请帮帮我。

非常感谢你。

1 个答案:

答案 0 :(得分:0)

我在https://httpbin.org/的帮助下调试了这个。首先,我复制了你的curl命令发送到那里:

curl -v -u aa:bb -X POST httpbin.org/post -H "Accept: application/json; version=0" -H "Content-Type:application/json" -d '{"login": "username", "password": "secret", "email":"my_email"}'

它返回了:

{
  "args": {}, 
  "data": "{\"login\": \"username\", \"password\": \"secret\", \"email\":\"my_email\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "application/json; version=0", 
    "Authorization": "Basic YWE6YmI=", 
    "Content-Length": "63", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "curl/7.43.0"
  }, 
  "json": {
    "email": "my_email", 
    "login": "username", 
    "password": "secret"
  }, 
  "origin": "197.155.4.24", 
  "url": "http://httpbin.org/post"
}

然后我修改了你的代码,在通过argparse传递参数后,将相同的请求发送到同一个地方。回应看起来很相似。我将这两者与PyCharm'与剪贴板比较'功能(虽然任何差异工具都可以),问题变得清晰:

The difference

您在代码中交换了密码和电子邮件!我很抱歉。