Alternating Variables That Run

I want to use different API keys to collect data every time my program starts.

For example, I have the following two keys:

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

and the following URL:

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

When the program starts, I would like to myUrluse apiKey1. As soon as it starts up again, I would like it to use apiKey2etc ... ie:

First start:

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

Second run:

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

Sorry if that doesn't make sense, but does anyone know a way to do this? I have no idea.


EDIT:

To avoid confusion, I reviewed this answer. But this does not answer my request. My goal is to switch between variables between running my script.

+6
3

, , :

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')
+1

( , ). , , .

, : 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() - , .

, :

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

, , .

+2

, , , , script , .

, - redis, (?) , , , . redis - , , , - .

, :

  • , redis-server ( , )
  • Python redis
  • , Python :

    import redis

    db = redis.Redis()

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

    

!

0
source

Source: https://habr.com/ru/post/1016713/


All Articles