2017-04-23 46 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 

    

这就是它!