如何在Python中的for循环块之外“增加”变量?

时间:2016-09-08 20:10:59

标签: python

我有以下代码:

#!/usr/bin/python

import time
import uuid
import hmac
import hashlib
import base64
import json
import urllib3
import certifi
import datetime
import requests
import re
from datetime import datetime

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED')  # Force certificatecheck.ca_certs = certifi.where(), #Path to the Certifi bundle.

# Get the status response from pritunl api

BASE_URL = 'https://<REDACTED>'
API_TOKEN = '<REDACTED>'
API_SECRET = '<REDACTED>'
LOG_PATH = '/var/log/logfiles/'


def auth_request(
    method,
    path,
    headers=None,
    data=None,
    ):
    auth_timestamp = str(int(time.time()))


auth_nonce = uuid.uuid4().hex
auth_string = '&'.join([API_TOKEN, auth_timestamp, auth_nonce,
                       method.upper(), path]
                       + (([data] if data else [])))
auth_signature = base64.b64encode(hmac.new(API_SECRET, auth_string,
                                  hashlib.sha256).digest())
auth_headers = {
    'Auth-Token': API_TOKEN,
    'Auth-Timestamp': auth_timestamp,
    'Auth-Nonce': auth_nonce,
    'Auth-Signature': auth_signature,
    }
if headers:
    auth_headers.update(headers)
return http.request(method, BASE_URL + path, headers=auth_headers,
                    body=data)

response1 = auth_request('GET', '/server')
if response1.status == 200:
    pritunlServResponse = json.loads(response1.data)  # print pritunlServResponse# print response1.data

    Name = [y['name'] for y in pritunlServResponse]
    Server_id = [x['id'] for x in pritunlServResponse]

    for srv_name in Name:
        for srv_id in Server_id:
            response2 = auth_request('GET', '/server/' + srv_id
                    + '/output')
            pritunlServResponse2 = json.loads(response2.data)
            py_pritunlServResponse2 = pritunlServResponse2['output']

            print ('value of srv_id: ', srv_id, '\n')
            print ('value of srv_name: ', srv_name, '\n')

            logfile = open(LOG_PATH + srv_name + '_vpn_out.log', 'w')
            for log in py_pritunlServResponse2:
                if re.search(r'(?!52\.39\.62\.8)', log):
                    logfile.write('%s\n' % log)

            logfile.close()
else:

    raise SystemExit

此代码使用身份验证访问网站(地址已被编辑),抓取一些用JSON格式化的文本,并从输出中解析两个值:“srv_name”和“srv_id”。然后,此代码使用“srv_id”构造其他HTTP请求以从服务器获取日志文件。然后它抓取日志文件 - 每个“srv_id”一个,并使用从“srv_name”获得的值命名它们。

编写的代码在语法上是正确的,但它不是我需要的。在编写时,有一个嵌套的for循环(对于Server_id :)中的srv_id在另一个for循环中(对于Name中的srv_name)。

我需要的是保持for循环(对于server_id :)中的srv_id,但是在每次通过srv_id的for循环之后“递增”服务器名称变量(将其移动到下一个值)(对于Server_id中的srv_id) :)这样我就可以拥有一个具有相应服务器名称的单独日志文件。

“固定”代码可能类似于:

#!/usr/bin/python

import time
import uuid
import hmac
import hashlib
import base64
import json
import urllib3
import certifi
import datetime
import requests
import re
from datetime import datetime

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED')  # Force certificate check.ca_certs = certifi.where(), #Path to the Certifi bundle.

# Get the status response from pritunl api

BASE_URL = 'https://<REDACTED>'
API_TOKEN = '<REDACTED>'
API_SECRET = '<REDACTED>'
LOG_PATH = '/var/log/logfiles/'


def auth_request(
    method,
    path,
    headers=None,
    data=None,
    ):
    auth_timestamp = str(int(time.time()))


auth_nonce = uuid.uuid4().hex
auth_string = '&'.join([API_TOKEN, auth_timestamp, auth_nonce,
                       method.upper(), path]
                       + (([data] if data else [])))
auth_signature = base64.b64encode(hmac.new(API_SECRET, auth_string,
                                  hashlib.sha256).digest())
auth_headers = {
    'Auth-Token': API_TOKEN,
    'Auth-Timestamp': auth_timestamp,
    'Auth-Nonce': auth_nonce,
    'Auth-Signature': auth_signature,
    }
if headers:
    auth_headers.update(headers)
return http.request(method, BASE_URL + path, headers=auth_headers,
                    body=data)

response1 = auth_request('GET', '/server')
if response1.status == 200:
    pritunlServResponse = json.loads(response1.data)  # print pritunlServResponse# print response1.data

    Name = [y['name'] for y in pritunlServResponse]
    Server_id = [x['id'] for x in pritunlServResponse]


    for srv_id in Server_id:
        response2 = auth_request('GET', '/server/' + srv_id
                + '/output')
        pritunlServResponse2 = json.loads(response2.data)
        py_pritunlServResponse2 = pritunlServResponse2['output']

        print ('value of srv_id: ', srv_id, '\n')
        print ('value of Name: ', Name, '\n')

        logfile = open(LOG_PATH + srv_name + '_vpn_out.log', 'w')
        for log in py_pritunlServResponse2:
            if re.search(r'(?!52\.39\.62\.8)', log):
                logfile.write('%s\n' % log)

        logfile.close()

        <CODE TO ADVANCE "Name">
else:

    raise SystemExit

2 个答案:

答案 0 :(得分:3)

也许像这样循环它有点不同?

for item in pritunlServResponse:
    srv_id = item['id']
    name = item['name']

这样你就不必在第一时间创建这些

Name = [y['name'] for y in pritunlServResponse]
Server_id = [x['id'] for x in pritunlServResponse]

答案 1 :(得分:2)

使用:

for srv_name, srv_id in zip(Name, Server_id):
    ...

更好的是,替换:

pritunlServResponse = json.loads(response1.data)

Name = [y['name'] for y in pritunlServResponse]
Server_id = [x['id'] for x in pritunlServResponse]

for srv_name in Name:
    for srv_id in Server_id:
        ...

使用:

for srv_name, srv_id in [(resp['name'], resp['id']) for resp in json.loads(response1.data)]:
    ...