2017-04-23 48 views
6

我想在每次運行程序時使用不同的API密鑰來抓取數據。每次運行變量之間交替

舉例來說,我有以下2項:

apiKey1 = "123abc" 
apiKey2 = "345def" 

及以下網址:

myUrl = http://myurl.com/key=... 

當運行程序,我想用myUrlapiKey1是。一旦它被再次運行,然後,我會喜歡它使用apiKey2等等...即:

首次運行:

url = "http://myurl.com/key=" + apiKey1 

第二輪:

url = "http://myurl.com/key=" + apiKey2 

很抱歉,如果這並未沒有道理,但是有沒有人知道一種方法來做到這一點?我不知道。


編輯:

爲了避免混淆,我看了一下this答案。但是這不能回答我的問題。我的目標是在執行腳本之間的變量之間循環。

+1

'對於itertools.cycle中的鍵((apiKey1,apiKey2)):'?什麼時候應該停止它們之間的切換? – jonrsharpe

+4

你的程序需要保持*狀態*。通常這是通過將信息寫入文件來完成的。此外,你幾乎肯定會違反你(ab)使用的API的服務條款。 –

+0

@jonrsharpe我也在想'循環',但我有一個預感,OP想要在他的腳本執行之間的變量之間循環。 – timgeb

回答

1

下面是如何,你可以,如果沒有這樣的文件存在自動創建文件做一個例子:

import os 
if not os.path.exists('Checker.txt'): 
    '''here you check whether the file exists 
    if not this bit creates it 
    if file exists nothing happens''' 
    with open('Checker.txt', 'w') as f: 
     #so if the file doesn't exist this will create it 
     f.write('0') 

myUrl = 'http://myurl.com/key=' 
apiKeys = ["123abc", "345def"] 

with open('Checker.txt', 'r') as f: 
    data = int(f.read()) #read the contents of data and turn it into int 
    myUrl = myUrl + apiKeys[data] #call the apiKey via index 

with open('Checker.txt', 'w') as f: 
    #rewriting the file and swapping values 
    if data == 1: 
     f.write('0') 
    else: 
     f.write('1') 
+0

這太棒了!非常感謝,如果你可以快速解釋代碼將是偉大的 – LearningToPython

+0

歡迎您!我添加了評論以幫助您瞭解過程。請問是否需要進一步澄清:) – zipa

+0

謝謝!這太好了;-) – LearningToPython

2

我會用一個持久的字典(它就像一個數據庫,但更輕巧)。這樣,您可以輕鬆存儲選項和下一個要訪問的選項。

有已經在標準庫庫,提供了這樣一個持久的詞典:shelve

import shelve 

filename = 'target.shelve' 

def get_next_target(): 
    with shelve.open(filename) as db: 
     if not db: 
      # Not created yet, initialize it: 
      db['current'] = 0 
      db['options'] = ["123abc", "345def"] 

     # Get the current option 
     nxt = db['options'][db['current']] 
     db['current'] = (db['current'] + 1) % len(db['options']) # increment with wraparound 

    return nxt 

而且每次調用get_next_target()將返回下一個選項 - 如果你把它無論多次在同一執行或每執行一次。如果你從來沒有超過2個選項

的邏輯可以簡化爲:

db['current'] = 0 if db['current'] == 1 else 1 

但我想這可能是值得有一種方法,可以輕鬆處理多個選項。

0

我會依靠一個外部進程來保存上次使用的密鑰, 甚至更​​簡單我會計算腳本的執行次數,如果執行計數是奇數,則使用密鑰,或者用於偶數的其他密鑰數。

所以我會介紹一些類似於redis的東西,這對於您可能希望添加到項目中的其他(未來?)功能也有很大幫助。 redis是那些幾乎可以免費獲得好處的工具之一,能夠依靠外部永久存儲非常實用 - 它可以用於多種用途。

因此,這裏是我會怎麼做:

  1. 首先確保Redis的服務器正在運行(可以作爲一個守護進程會自動啓動,取決於你的系統)
  2. 安裝Python Redis的模塊
  3. 那麼,這裏是一些Python代碼中尋找靈感:

    import redis 

    db = redis.Redis() 

    if db.hincrby('execution', 'count', 1) % 2: 
     key = apiKey1 
    else: 
     key = apiKey2 

    

這就是它!