-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathgenerate_key.py
68 lines (51 loc) · 2.09 KB
/
generate_key.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""
API Key Generator
This script will generate an API key for an Algolia application.
The generated key will be valid for Search operations, and will be limited to 100 queries per hour.
"""
from os import getenv
# Install the API client: https://www.algolia.com/doc/api-client/getting-started/install/python/?client=python
from algoliasearch.search_client import SearchClient
from dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv())
# Get your Algolia Application ID and (admin) API key from the dashboard: https://www.algolia.com/account/api-keys
# and choose a name for your index. Add these environment variables to a `.env` file:
ALGOLIA_APP_ID = getenv('ALGOLIA_APP_ID')
ALGOLIA_API_KEY = getenv('ALGOLIA_API_KEY')
ALGOLIA_INDEX_NAME = getenv('ALGOLIA_INDEX_NAME')
# Start the API client
# https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/
client = SearchClient.create(ALGOLIA_APP_ID, ALGOLIA_API_KEY)
# Create the key
#https://www.algolia.com/doc/api-reference/api-methods/add-api-key/?client=python
# Set the permissions for the key
acl = ['search']
# Set the parameters for the key
params = {
'description': 'Restricted search-only API key for algolia.com',
# Rate-limit to 100 requests per hour per IP address
'maxQueriesPerIPPerHour': 100
}
# Make the API request to add the key
print('Generating key...')
try:
res = client.add_api_key(acl, params).wait()
key = res['key']
print(f'Key generated successfully: {key}.')
except Exception as e:
print(f'Error generating key: {e}')
exit()
# Test the created key
print('Testing key...')
# Initialise a new client with the generated key
client = SearchClient.create(ALGOLIA_APP_ID, key)
# Create an index (or connect to it, if an index with the name `ALGOLIA_INDEX_NAME` already exists)
# https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/#initialize-an-index
index = client.init_index(ALGOLIA_INDEX_NAME)
try:
res = index.search('')
if res:
print('Key tested successfully')
except Exception as e:
print(f'Error testing key: {e}')
exit()