从用户处获取多个输入并将输入添加到JSON或Python中的Dictionary

时间:2018-06-20 10:30:09

标签: python list dictionary elasticsearch

我要从python脚本运行以下命令:

curl -XPUT 'localhost:9200/_snapshot/my_backup/snapshot_2?wait_for_completion=true&pretty' -H 'Content-Type: application/json' -d'
{
  "indices": "index_1,index_2",
  "ignore_unavailable": true,
  "include_global_state": false
}'

对于以上命令,我想从用户的索引下获取索引。它可以是多个索引或单个条目。现在我只能取一个值。

这是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from collections import defaultdict
import urllib2
import requests
from random import randrange
from requests.auth import HTTPBasicAuth
import sys
import threading
reload(sys)
sys.setdefaultencoding("utf-8")

headers = {'Content-Type': 'application/json'}
data = {"type": "fs", "settings": {"location": "/home/gnsarchlab/backup"}}
tmpdict = defaultdict()
tmpdict = json.dumps(data)
method=""

def initialiseSnapshot():

    response=requests.put('http://localhost:9200/_snapshot/my_backup?pretty',headers=headers,data = tmpdict)
    print response
    if(response.status_code != None and response.status_code == 200):
        print "Snapshot Initiated"
        print response.status_code

    else:
        print "Error initialsing snapshot"
        print response.status_code


def validatingRepository():

    response=requests.get('http://localhost:9200/_snapshot/my_backup?pretty') 
    print response

    if(response.status_code != None and response.status_code == 200):
        print "Repository Validated"
        print response.status_code

    else:
        print "Error validating repository"
        print response.status_code

def capturingSnapshot():

    print "Enter 0 for taking snapshot of all the indices."
    print "Enter 1 to give the name of the indice"
    indice = int(raw_input())
    if indice == 0:
        response=requests.put('http://localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true&pretty')
        print response 

        if(response.status_code != None and response.status_code == 200):
            print "Snapshot Captured"

        else:
            print "Error capturing snapshot"

    if indice == 1:
        indice_name_list = []
        data1 = {"ignore_unavailable": "true", "include_global_state": "false"}
        while True:
            indice_name = raw_input("Enter indice(s) (Type 'q' to quit): ")
            if indice_name == 'q':
                break
            indice_name_list.append(indice_name)
        print(indice_name_list)
        data1['indices'] = indice_name_list
        print data1
        datadict = json.dumps(data1)
        print datadict
        response1=requests.put('localhost:9200/_snapshot/my_backup/snapshot_2?wait_for_completion=true&pretty',data=datadict)
        print response

        if(response.status_code != None and response.status_code == 200):
            print "Snapshot Captured"

        else:
            print "Error capturing snapshot"


if __name__ == "__main__":

    if(len(sys.argv) < 2):
        print "Usage : python snapshot_script_take_indice_name.py [initialise|validate|capture|all]"
    elif(sys.argv[1] == "initialise"or sys.argv[1] == "is"):
        initialiseSnapshot()
    elif(sys.argv[1] == "validate" or sys.argv[1] == "vr"):
        validatingRepository()
    elif(sys.argv[1] == 'capture' or sys.argv[1] == "cs"):
        capturingSnapshot()
    elif(sys.argv[1] == 'all'):
        initialiseSnapshot()
        validatingRepository()
        capturingSnapshot()

当我尝试将数据追加到captureSnapshot()函数中时,我的数据如下:

['portal', 'stargate_topo_info'] - indice_name_list
{'indices': ['portal', 'stargate_topo_info'], 'ignore_unavailable': 'true', 'include_global_state': 'false'} - data1
{"indices": ["portal", "stargate_topo_info"], "ignore_unavailable": "true", "include_global_state": "false"} - datadict

应采用以下格式:

{
      "indices": "index_1,index_2",
      "ignore_unavailable": true,
      "include_global_state": false
    }

这仅在列表中发生。当我使用单个值(而不是通过列表)时,它工作正常。

我在做什么错?

0 个答案:

没有答案