Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,8 @@
|
|
1 |
import logging
|
2 |
from typing import Optional
|
3 |
-
|
4 |
-
import
|
5 |
-
import random
|
6 |
-
import string
|
7 |
-
import datetime
|
8 |
from webscout import WEBS
|
9 |
-
from functools import wraps
|
10 |
import requests
|
11 |
|
12 |
app = Flask(__name__)
|
@@ -14,69 +10,23 @@ app = Flask(__name__)
|
|
14 |
TIMEOUT = 10
|
15 |
PROXY = None
|
16 |
|
17 |
-
PRICING_PLANS = {
|
18 |
-
'free': {
|
19 |
-
'name': 'Free Plan',
|
20 |
-
'price': '$0/month',
|
21 |
-
'rate_limit': 1000
|
22 |
-
},
|
23 |
-
'pro': {
|
24 |
-
'name': 'Pro Plan',
|
25 |
-
'price': 'Coming Soon',
|
26 |
-
'rate_limit': None # Unlimited
|
27 |
-
}
|
28 |
-
}
|
29 |
-
|
30 |
-
# Function to generate a new API key based on the user's name and the current date
|
31 |
-
def generate_api_key(username):
|
32 |
-
"""Generate a new API key starting with 'HUAI' and including the user's name and the current date."""
|
33 |
-
current_date = datetime.datetime.now().strftime("%Y%m%d")
|
34 |
-
return 'HUAI' + username + current_date + ''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
|
35 |
-
|
36 |
-
# Function to validate an API key against the stored keys
|
37 |
-
def validate_api_key(api_key):
|
38 |
-
"""Validate an API key against the stored keys."""
|
39 |
-
with open('api_keys.json', 'r') as file:
|
40 |
-
api_keys = json.load(file)
|
41 |
-
return api_key in api_keys.values()
|
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):
|
47 |
-
# Check if the API key is provided in the headers
|
48 |
-
api_key = request.headers.get('HUSI')
|
49 |
-
|
50 |
-
# If not provided in headers, check query parameters
|
51 |
-
if not api_key:
|
52 |
-
api_key = request.args.get('HUAI')
|
53 |
-
|
54 |
-
if not validate_api_key(api_key):
|
55 |
-
abort(401) # Unauthorized
|
56 |
-
return view_function(*args, **kwargs)
|
57 |
-
return decorated_function
|
58 |
-
|
59 |
-
|
60 |
-
# Routes with API key requirement
|
61 |
-
|
62 |
@app.route('/api/search', methods=['GET'])
|
63 |
-
@require_api_key
|
64 |
def search_text():
|
65 |
-
|
66 |
query = request.args.get('q', '')
|
67 |
max_results = request.args.get('max_results', 10, type=int)
|
68 |
timelimit = request.args.get('timelimit', None)
|
69 |
safesearch = request.args.get('safesearch', 'moderate')
|
70 |
region = request.args.get('region', 'wt-wt')
|
71 |
-
WEBS_instance = WEBS()
|
72 |
results = []
|
73 |
with WEBS() as webs:
|
74 |
for result in enumerate(WEBS_instance.text(query, max_results=max_results, timelimit=timelimit, safesearch=safesearch, region=region)):
|
75 |
results.append(result)
|
|
|
76 |
return jsonify({'results': results})
|
77 |
|
|
|
78 |
@app.route('/api/images', methods=['GET'])
|
79 |
-
@require_api_key
|
80 |
def search_images():
|
81 |
query = request.args.get('q', '')
|
82 |
max_results = request.args.get('max_results', 10, type=int)
|
@@ -87,10 +37,10 @@ def search_images():
|
|
87 |
with WEBS() as webs:
|
88 |
for result in enumerate(WEBS_instance.images(query, max_results=max_results, safesearch=safesearch, region=region)):
|
89 |
results.append(result)
|
|
|
90 |
return jsonify({'results': results})
|
91 |
|
92 |
@app.route('/api/videos', methods=['GET'])
|
93 |
-
@require_api_key
|
94 |
def search_videos():
|
95 |
query = request.args.get('q', '')
|
96 |
max_results = request.args.get('max_results', 10, type=int)
|
@@ -104,10 +54,10 @@ def search_videos():
|
|
104 |
with WEBS() as webs:
|
105 |
for result in enumerate(WEBS_instance.videos(query, max_results=max_results, safesearch=safesearch, region=region, timelimit=timelimit, resolution=resolution, duration=duration)):
|
106 |
results.append(result)
|
|
|
107 |
return jsonify({'results': results})
|
108 |
|
109 |
@app.route('/api/news', methods=['GET'])
|
110 |
-
@require_api_key
|
111 |
def search_news():
|
112 |
query = request.args.get('q', '')
|
113 |
max_results = request.args.get('max_results', 10, type=int)
|
@@ -119,10 +69,10 @@ def search_news():
|
|
119 |
with WEBS() as webs:
|
120 |
for result in enumerate(WEBS_instance.news(query, max_results=max_results, safesearch=safesearch, region=region, timelimit=timelimit)):
|
121 |
results.append(result)
|
|
|
122 |
return jsonify({'results': results})
|
123 |
|
124 |
@app.route('/api/maps', methods=['GET'])
|
125 |
-
@require_api_key
|
126 |
def search_maps():
|
127 |
query = request.args.get('q', '')
|
128 |
place = request.args.get('place', None)
|
@@ -132,24 +82,25 @@ def search_maps():
|
|
132 |
with WEBS() as webs:
|
133 |
for result in enumerate(WEBS_instance.maps(query, place=place, max_results=max_results)):
|
134 |
results.append(result)
|
|
|
135 |
return jsonify({'results': results})
|
136 |
|
137 |
@app.route('/api/translate', methods=['GET'])
|
138 |
-
@require_api_key
|
139 |
def translate_text():
|
140 |
query = request.args.get('q', '')
|
141 |
to_lang = request.args.get('to', 'en')
|
142 |
WEBS_instance = WEBS()
|
143 |
with WEBS() as webs:
|
144 |
translation = enumerate(WEBS_instance.translate(query, to=to_lang))
|
|
|
145 |
return jsonify({'translation': translation})
|
146 |
|
147 |
@app.route('/api/suggestions', methods=['GET'])
|
148 |
-
@require_api_key
|
149 |
def search_suggestions():
|
150 |
query = request.args.get('q', '')
|
151 |
if not query:
|
152 |
return jsonify({'error': 'Query parameter missing'})
|
|
|
153 |
results = []
|
154 |
try:
|
155 |
with WEBS() as webs:
|
@@ -157,74 +108,12 @@ def search_suggestions():
|
|
157 |
results.append(result)
|
158 |
except Exception as e:
|
159 |
return jsonify({'error': str(e)}), 500
|
|
|
160 |
return jsonify({'results': results})
|
161 |
|
162 |
@app.route('/api/health', methods=['GET'])
|
163 |
-
@require_api_key
|
164 |
def health_check():
|
165 |
return jsonify({'status': 'working'})
|
166 |
|
167 |
-
import json
|
168 |
-
from flask import jsonify, request, abort
|
169 |
-
|
170 |
-
@app.route('/pricing', methods=['GET'])
|
171 |
-
def pricing():
|
172 |
-
return render_template('pricing.html', plans=PRICING_PLANS)
|
173 |
-
|
174 |
-
|
175 |
-
@app.route('/generate_key', methods=['GET', 'POST'])
|
176 |
-
def generate_key():
|
177 |
-
if request.method == 'POST':
|
178 |
-
username = request.form['username']
|
179 |
-
plan = request.form['plan']
|
180 |
-
if plan not in PRICING_PLANS:
|
181 |
-
return jsonify({'error': 'Invalid plan'}), 400
|
182 |
-
if plan == 'free' and PRICING_PLANS['free']['rate_limit'] == 0:
|
183 |
-
return jsonify({'error': 'Free plan is out of limits'}), 400
|
184 |
-
|
185 |
-
# Check if the user already has an API key
|
186 |
-
with open('api_keys.json', 'r') as file:
|
187 |
-
try:
|
188 |
-
api_keys = json.load(file)
|
189 |
-
except json.JSONDecodeError:
|
190 |
-
# If the file is empty or contains invalid JSON, initialize api_keys as an empty dict
|
191 |
-
api_keys = {}
|
192 |
-
|
193 |
-
if username in api_keys:
|
194 |
-
return jsonify({'api_key': api_keys[username]})
|
195 |
-
|
196 |
-
# Generate a new API key
|
197 |
-
new_key = generate_api_key(username)
|
198 |
-
try:
|
199 |
-
with open('api_keys.json', 'w') as file:
|
200 |
-
api_keys[username] = new_key
|
201 |
-
json.dump(api_keys, file, indent=4)
|
202 |
-
return jsonify({'api_key': new_key})
|
203 |
-
except Exception as e:
|
204 |
-
# Handle any other exceptions that might occur
|
205 |
-
return jsonify({'error': str(e)}), 500
|
206 |
-
else:
|
207 |
-
return render_template('index.html', plans=PRICING_PLANS)
|
208 |
if __name__ == '__main__':
|
209 |
-
|
210 |
-
try:
|
211 |
-
response = requests.get('https://api.ipify.org/?format=json')
|
212 |
-
response.raise_for_status() # Raises a HTTPError if the response status is 4xx, 5xx
|
213 |
-
data = response.json()
|
214 |
-
return data['ip']
|
215 |
-
except requests.exceptions.RequestException as e:
|
216 |
-
print(f"An error occurred: {e}")
|
217 |
-
return None
|
218 |
-
except Exception as e:
|
219 |
-
print(f"An unexpected error occurred: {e}")
|
220 |
-
return None
|
221 |
-
|
222 |
-
# Get public IP or use a fallback
|
223 |
-
public_ip = get_public_ip() or 'Fallback_IP'
|
224 |
-
|
225 |
-
if public_ip:
|
226 |
-
print(f"Public IP: {public_ip}")
|
227 |
-
else:
|
228 |
-
print("Failed to retrieve public IP. Using fallback IP.")
|
229 |
-
|
230 |
-
app.run(debug=True)
|
|
|
1 |
import logging
|
2 |
from typing import Optional
|
3 |
+
|
4 |
+
from flask import Flask, jsonify, request
|
|
|
|
|
|
|
5 |
from webscout import WEBS
|
|
|
6 |
import requests
|
7 |
|
8 |
app = Flask(__name__)
|
|
|
10 |
TIMEOUT = 10
|
11 |
PROXY = None
|
12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
@app.route('/api/search', methods=['GET'])
|
|
|
14 |
def search_text():
|
|
|
15 |
query = request.args.get('q', '')
|
16 |
max_results = request.args.get('max_results', 10, type=int)
|
17 |
timelimit = request.args.get('timelimit', None)
|
18 |
safesearch = request.args.get('safesearch', 'moderate')
|
19 |
region = request.args.get('region', 'wt-wt')
|
20 |
+
WEBS_instance = WEBS() # Instantiate WEBS without context manager
|
21 |
results = []
|
22 |
with WEBS() as webs:
|
23 |
for result in enumerate(WEBS_instance.text(query, max_results=max_results, timelimit=timelimit, safesearch=safesearch, region=region)):
|
24 |
results.append(result)
|
25 |
+
|
26 |
return jsonify({'results': results})
|
27 |
|
28 |
+
|
29 |
@app.route('/api/images', methods=['GET'])
|
|
|
30 |
def search_images():
|
31 |
query = request.args.get('q', '')
|
32 |
max_results = request.args.get('max_results', 10, type=int)
|
|
|
37 |
with WEBS() as webs:
|
38 |
for result in enumerate(WEBS_instance.images(query, max_results=max_results, safesearch=safesearch, region=region)):
|
39 |
results.append(result)
|
40 |
+
|
41 |
return jsonify({'results': results})
|
42 |
|
43 |
@app.route('/api/videos', methods=['GET'])
|
|
|
44 |
def search_videos():
|
45 |
query = request.args.get('q', '')
|
46 |
max_results = request.args.get('max_results', 10, type=int)
|
|
|
54 |
with WEBS() as webs:
|
55 |
for result in enumerate(WEBS_instance.videos(query, max_results=max_results, safesearch=safesearch, region=region, timelimit=timelimit, resolution=resolution, duration=duration)):
|
56 |
results.append(result)
|
57 |
+
|
58 |
return jsonify({'results': results})
|
59 |
|
60 |
@app.route('/api/news', methods=['GET'])
|
|
|
61 |
def search_news():
|
62 |
query = request.args.get('q', '')
|
63 |
max_results = request.args.get('max_results', 10, type=int)
|
|
|
69 |
with WEBS() as webs:
|
70 |
for result in enumerate(WEBS_instance.news(query, max_results=max_results, safesearch=safesearch, region=region, timelimit=timelimit)):
|
71 |
results.append(result)
|
72 |
+
|
73 |
return jsonify({'results': results})
|
74 |
|
75 |
@app.route('/api/maps', methods=['GET'])
|
|
|
76 |
def search_maps():
|
77 |
query = request.args.get('q', '')
|
78 |
place = request.args.get('place', None)
|
|
|
82 |
with WEBS() as webs:
|
83 |
for result in enumerate(WEBS_instance.maps(query, place=place, max_results=max_results)):
|
84 |
results.append(result)
|
85 |
+
|
86 |
return jsonify({'results': results})
|
87 |
|
88 |
@app.route('/api/translate', methods=['GET'])
|
|
|
89 |
def translate_text():
|
90 |
query = request.args.get('q', '')
|
91 |
to_lang = request.args.get('to', 'en')
|
92 |
WEBS_instance = WEBS()
|
93 |
with WEBS() as webs:
|
94 |
translation = enumerate(WEBS_instance.translate(query, to=to_lang))
|
95 |
+
|
96 |
return jsonify({'translation': translation})
|
97 |
|
98 |
@app.route('/api/suggestions', methods=['GET'])
|
|
|
99 |
def search_suggestions():
|
100 |
query = request.args.get('q', '')
|
101 |
if not query:
|
102 |
return jsonify({'error': 'Query parameter missing'})
|
103 |
+
|
104 |
results = []
|
105 |
try:
|
106 |
with WEBS() as webs:
|
|
|
108 |
results.append(result)
|
109 |
except Exception as e:
|
110 |
return jsonify({'error': str(e)}), 500
|
111 |
+
|
112 |
return jsonify({'results': results})
|
113 |
|
114 |
@app.route('/api/health', methods=['GET'])
|
|
|
115 |
def health_check():
|
116 |
return jsonify({'status': 'working'})
|
117 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
118 |
if __name__ == '__main__':
|
119 |
+
app.run()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|