简体   繁体   English

循环更改Python 2.7中的参数

[英]Loop through to change parameter in Python 2.7

So I have this code that is creating an output in Excel. 因此,我有这段代码正在Excel中创建输出。 What I want to do now is get the parameters (lid) in payload to loop through a list of other ID's 我现在想做的是获取有效负载中的参数(盖)以遍历其他ID的列表

This list is stored in a txt file. 此列表存储在txt文件中。

can anyone modify my code to show me how to do that please? 谁能修改我的代码以向我展示如何执行此操作? The text file has values 1654, 3457, 4327, 1234 文本文件的值是1654、3457、4327、1234

(can also hard code these somewhere in the script if it is easier) (如果更容易的话,也可以在脚本中的某处硬编码这些代码)

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()

Why not just pass all the lid values as a parameter to your retrieve_data function. 为什么不只将所有的盖度值作为参数传递给您的restore_data函数。

def retrieve_data(api_url):

would become 会成为

def retrieve_data(api_url, lid_value):

You would remove the hardcoded lid section of your payload so the payload would look like this 您将删除有效载荷的硬编码lid部分,以便有效载荷看起来像这样

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

Then on the next line you can add 然后在下一行您可以添加

payload['lid'] = lid_value

In your main function you could then loop through the values in the text file. 然后,您可以在主要功能中循环浏览文本文件中的值。 Here is a simple loop with a list. 这是一个带有列表的简单循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM