File size: 2,845 Bytes
5b025ef |
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 68 69 70 71 72 73 74 75 |
from flask import Flask, request, Response
import requests
from cachetools import TTLCache
app = Flask(__name__)
# Configure the cache
cache = TTLCache(maxsize=1000000, ttl=30000) # Cache up to 1000 entries for 5 minutes
# NextDNS endpoint
NEXTDNS_ENDPOINT = "https://dns.nextdns.io/7df33f"
# Stats counters
total_requests = 0
cache_misses = 0
cache_hits = 0
@app.route('/', methods=['GET', 'POST'])
def handle_request():
global total_requests, cache_misses, cache_hits
total_requests += 1
# Handle GET requests with 'dns' parameter
if request.method == 'GET' and 'dns' in request.args:
dns_query = request.args.get('dns')
cached_response = cache.get(dns_query)
if cached_response:
cache_hits += 1
return Response(cached_response, mimetype='application/dns-message')
else:
cache_misses += 1
response = requests.get(f"{NEXTDNS_ENDPOINT}?dns={dns_query}", headers={'Accept': 'application/dns-message'})
if response.status_code == 200:
cache[dns_query] = response.content
return Response(response.content, mimetype='application/dns-message')
# Handle POST requests with 'application/dns-message' content type
elif request.method == 'POST' and request.headers.get('Content-Type') == 'application/dns-message':
dns_query = request.data
cached_response = cache.get(dns_query)
if cached_response:
cache_hits += 1
return Response(cached_response, mimetype='application/dns-message')
else:
cache_misses += 1
response = requests.post(NEXTDNS_ENDPOINT, headers={'Accept': 'application/dns-message', 'Content-Type': 'application/dns-message'}, data=dns_query)
if response.status_code == 200:
cache[dns_query] = response.content
return Response(response.content, mimetype='application/dns-message')
# Handle GET requests with 'application/dns-json' Accept header
elif request.method == 'GET' and request.headers.get('Accept') == 'application/dns-json':
# Assuming JSON queries are not cached for simplicity, adjust as needed
total_requests += 1
cache_misses += 1
response = requests.get(NEXTDNS_ENDPOINT + request.full_path, headers={'Accept': 'application/dns-json'})
return Response(response.content, mimetype='application/dns-json')
# Return an error for unsupported requests
else:
return Response("DoH Gateway Provided by NextDNS", status=444)
@app.route('/stats')
def show_stats():
stats = f"""
============
Total DNS Request: {total_requests}
Domain Cached: {cache_misses}
Domain Cached Hit: {cache_hits}
============
"""
return stats
if __name__ == '__main__':
app.run(debug=True, port=7860) |