Update app.py
Browse files
app.py
CHANGED
@@ -24,23 +24,35 @@ PRICING_PLANS = {
|
|
24 |
'pro': {
|
25 |
'name': 'Pro Plan',
|
26 |
'price': 'Coming Soon',
|
27 |
-
'rate_limit': None
|
28 |
}
|
29 |
}
|
30 |
|
31 |
-
# Define the
|
32 |
API_KEYS_DIRECTORY = os.path.join(os.getcwd(), 'static', 'data')
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
|
34 |
# Function to generate a new API key and save it to a file
|
35 |
-
def generate_api_key(
|
36 |
current_date = datetime.datetime.now().strftime("%Y%m%d")
|
|
|
37 |
api_key = 'HUAI' + username + current_date + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
|
|
|
|
|
|
|
|
|
38 |
# Save the API key to a file
|
39 |
-
with open(os.path.join(
|
40 |
file.write(api_key)
|
41 |
return api_key
|
42 |
|
43 |
-
# Middleware to require an API key for each request
|
|
|
44 |
def require_api_key(view_function):
|
45 |
@wraps(view_function)
|
46 |
def decorated_function(*args, **kwargs):
|
@@ -51,21 +63,50 @@ def require_api_key(view_function):
|
|
51 |
if not api_key:
|
52 |
api_key = request.args.get('HUAI')
|
53 |
|
|
|
|
|
|
|
54 |
if not validate_api_key(api_key):
|
55 |
-
abort(401)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
return view_function(*args, **kwargs)
|
57 |
return decorated_function
|
58 |
|
|
|
59 |
# Function to validate an API key by checking if it matches any file in the directory
|
60 |
def validate_api_key(api_key):
|
61 |
-
|
62 |
-
|
|
|
63 |
with open(filepath, 'r') as file:
|
64 |
if file.read().strip() == api_key:
|
65 |
return True
|
66 |
return False
|
67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
# Routes with API key requirement
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
@app.route('/api/search', methods=['GET'])
|
71 |
@require_api_key
|
@@ -183,26 +224,14 @@ def pricing():
|
|
183 |
@app.route('/generate_key', methods=['GET', 'POST'])
|
184 |
def generate_key():
|
185 |
if request.method == 'POST':
|
186 |
-
username
|
187 |
-
|
188 |
-
|
189 |
-
if not username:
|
190 |
-
return jsonify({'error': 'Username not provided'}), 400
|
191 |
-
|
192 |
-
if plan not in PRICING_PLANS:
|
193 |
-
return jsonify({'error': 'Invalid plan'}), 400
|
194 |
-
|
195 |
-
# Check if the user already has an API key
|
196 |
-
for filename in os.listdir(API_KEYS_DIRECTORY):
|
197 |
-
if filename.startswith(username):
|
198 |
-
return jsonify({'error': 'API key already exists for this username'}), 400
|
199 |
-
|
200 |
-
# Generate a new API key
|
201 |
-
api_key = generate_api_key(username)
|
202 |
|
203 |
return jsonify({'api_key': api_key}), 201
|
204 |
else:
|
205 |
# Render the form for GET requests
|
206 |
return render_template('index.html', plans=PRICING_PLANS)
|
|
|
207 |
if __name__ == '__main__':
|
208 |
-
app.run(debug=True)
|
|
|
|
24 |
'pro': {
|
25 |
'name': 'Pro Plan',
|
26 |
'price': 'Coming Soon',
|
27 |
+
'rate_limit': None # Unlimited
|
28 |
}
|
29 |
}
|
30 |
|
31 |
+
# Define the directories for API keys
|
32 |
API_KEYS_DIRECTORY = os.path.join(os.getcwd(), 'static', 'data')
|
33 |
+
FREE_API_KEYS_DIRECTORY = os.path.join(API_KEYS_DIRECTORY, 'free')
|
34 |
+
PAID_API_KEYS_DIRECTORY = os.path.join(API_KEYS_DIRECTORY, 'paid')
|
35 |
+
|
36 |
+
# Ensure directories exist
|
37 |
+
os.makedirs(FREE_API_KEYS_DIRECTORY, exist_ok=True)
|
38 |
+
os.makedirs(PAID_API_KEYS_DIRECTORY, exist_ok=True)
|
39 |
|
40 |
# Function to generate a new API key and save it to a file
|
41 |
+
def generate_api_key():
|
42 |
current_date = datetime.datetime.now().strftime("%Y%m%d")
|
43 |
+
username = ''.join(random.choices(string.ascii_lowercase + string.digits, k=4)) # Generate a 4-character username
|
44 |
api_key = 'HUAI' + username + current_date + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
|
45 |
+
|
46 |
+
# Determine the directory based on the plan
|
47 |
+
api_keys_directory = FREE_API_KEYS_DIRECTORY if request.form.get('plan') == 'free' else PAID_API_KEYS_DIRECTORY
|
48 |
+
|
49 |
# Save the API key to a file
|
50 |
+
with open(os.path.join(api_keys_directory, username + '.txt'), 'w') as file:
|
51 |
file.write(api_key)
|
52 |
return api_key
|
53 |
|
54 |
+
# Middleware to require an API key for each request and enforce rate limits for free plan
|
55 |
+
# Middleware to require an API key for each request and enforce rate limits for free plan
|
56 |
def require_api_key(view_function):
|
57 |
@wraps(view_function)
|
58 |
def decorated_function(*args, **kwargs):
|
|
|
63 |
if not api_key:
|
64 |
api_key = request.args.get('HUAI')
|
65 |
|
66 |
+
if not api_key:
|
67 |
+
abort(401) # Unauthorized
|
68 |
+
|
69 |
if not validate_api_key(api_key):
|
70 |
+
abort(401) # Unauthorized
|
71 |
+
|
72 |
+
# Check if it's a free plan and enforce rate limit
|
73 |
+
if request.form.get('plan') == 'free':
|
74 |
+
username = api_key[4:8] # Extract username from API key
|
75 |
+
if not check_rate_limit(username):
|
76 |
+
abort(429) # Too Many Requests
|
77 |
+
|
78 |
return view_function(*args, **kwargs)
|
79 |
return decorated_function
|
80 |
|
81 |
+
|
82 |
# Function to validate an API key by checking if it matches any file in the directory
|
83 |
def validate_api_key(api_key):
|
84 |
+
api_keys_directory = FREE_API_KEYS_DIRECTORY if api_key.startswith('HUAI') else PAID_API_KEYS_DIRECTORY
|
85 |
+
for filename in os.listdir(api_keys_directory):
|
86 |
+
filepath = os.path.join(api_keys_directory, filename)
|
87 |
with open(filepath, 'r') as file:
|
88 |
if file.read().strip() == api_key:
|
89 |
return True
|
90 |
return False
|
91 |
|
92 |
+
# Function to check rate limit for free plan
|
93 |
+
|
94 |
+
def check_rate_limit(username):
|
95 |
+
today_date = datetime.datetime.now().strftime("%Y%m%d")
|
96 |
+
# Count the number of requests made by the user today
|
97 |
+
requests_count = sum(1 for _ in os.listdir(FREE_API_KEYS_DIRECTORY) if _.startswith(username + '_' + today_date))
|
98 |
+
return requests_count
|
99 |
+
|
100 |
# Routes with API key requirement
|
101 |
+
@app.route('/api/usage', methods=['GET'])
|
102 |
+
@require_api_key
|
103 |
+
def get_api_usage():
|
104 |
+
# Extract username from API key
|
105 |
+
api_key = request.headers.get('HUSI') or request.args.get('HUAI')
|
106 |
+
username = api_key[4:8]
|
107 |
+
# Get the usage count for the user
|
108 |
+
usage_count = check_rate_limit(username)
|
109 |
+
return jsonify({'username': username, 'usage_count': usage_count})
|
110 |
|
111 |
@app.route('/api/search', methods=['GET'])
|
112 |
@require_api_key
|
|
|
224 |
@app.route('/generate_key', methods=['GET', 'POST'])
|
225 |
def generate_key():
|
226 |
if request.method == 'POST':
|
227 |
+
# Generate a new API key with a random username (userid)
|
228 |
+
api_key = generate_api_key()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
|
230 |
return jsonify({'api_key': api_key}), 201
|
231 |
else:
|
232 |
# Render the form for GET requests
|
233 |
return render_template('index.html', plans=PRICING_PLANS)
|
234 |
+
|
235 |
if __name__ == '__main__':
|
236 |
+
app.run(debug=True)
|
237 |
+
|