【问题标题】:Loop through to change parameter in Python 2.7在 Python 2.7 中循环更改参数
【发布时间】:2014-10-03 21:31:14
【问题描述】:

所以我有这段代码在 Excel 中创建输出。 我现在要做的是获取有效负载中的参数(盖子)以循环遍历其他 ID 的列表

此列表存储在 txt 文件中。

任何人都可以修改我的代码来告诉我怎么做吗? 文本文件有值 1654, 3457, 4327, 第1234章

(如果更容易的话,也可以在脚本中的某处硬编码)

from __future__ import print_function
import sys
import csv
import collections
import itertools
try:
    import requests
    from requests import exceptions
    import base64
    import json
except ImportError as e:
    import requests
    from requests import exceptions
    import base64
    import json
    print ("Import Error: %s" % e)

API_TOKEN = u''

b64token = base64.b64encode(bytes(API_TOKEN))


REST_BASE_URL = u'https://visdasa.dsds.com/rest/'

# API URL request examples (choose one)
REST_URL = u'rawdata/'

FULL_URL = REST_BASE_URL + REST_URL

def retrieve_data(api_url):

    try:
        #connect to the API and retrieve data
        bauth_header = {'Authorization': 'Basic '+b64token.decode('UTF-8')}
        payload = {'start': '2014-08-01T00:00:01', 'stop': '2014-  8-01T23:59:59','category': 'ots','lid': '9263'}

        response = requests.get(api_url, headers=bauth_header, params=payload)
        # check the api response
        if response.status_code == requests.codes.ok:

            # Convert from json data
            json_data = json.loads(response.text)


            Header_String = "ID", "Site Name", "Network ID", "Network Lablel", "Company Branch ID", "Comapany Label","Count", "timestamp", "ots_duration", "notsure1", "notsure2"
            for location_row in json_data["data"]["locations"]:
                Location_string = (location_row["id"], location_row["label"], location_row["site"]["network"]["id"],location_row["site"]["network"]["label"],
                                location_row["site"]["id"], location_row["site"]["label"])

            try:

                with open('C:\\Users\\teddy\\Desktop\\party\\test.csv', 'w') as wFile:
                    writer = csv.writer(wFile, delimiter=',')
                    writer.write(Header_string)
                    for row in json_data["data"]["raw_data"]:
                        writer.writerow(row)

            except IOError as e:
                logger.error("I/O error({0}): {1}".format(e.errno, e.strerror))
                print( "I/O error({0}): {1}".format(e.errno, e.strerror))  


            else:
                    json_data = json.loads(response.text)
            # If not successful api call the throw an error
            raise requests.RequestException("Error with the api. Status code : %i \n Json response: %s"
                                            % (response.status_code, json_data))

    except (requests.exceptions.ProxyError, requests.RequestException) as e:
        print (e)


def main():

    #retrieve_data(FULL_URL, PROXY_SETTINGS)
    retrieve_data(FULL_URL)
    sys.exit()

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python loops python-2.7 dynamic parameter-passing


    【解决方案1】:

    为什么不将所有的盖子值作为参数传递给您的retrieve_data 函数。

    def retrieve_data(api_url):
    

    会变成

    def retrieve_data(api_url, lid_value):
    

    您将删除有效负载的硬编码lid 部分,使有效负载看起来像这样

    payload = {'start': '2014-08-01T00:00:01', 'stop': '2014-  8-01T23:59:59','category': 'ots'}
    

    然后你可以在下一行添加

    payload['lid'] = lid_value
    

    然后,您可以在您的 main 函数中循环遍历文本文件中的值。这是一个带有列表的简单循环。

    def main():
        lid_values = ['1654', '3457', '4327', '1234']
        for lid in lid_values:
            retrieve_data(FULL_URL, lid)
        sys.exit()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 2017-09-20
      • 2017-12-11
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多