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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| from flask import Flask, request, redirect, url_for import json import random import string import time from collections import OrderedDict import logging import re
app = Flask(__name__) logging.basicConfig(filename='app.log', level=logging.ERROR)
def nowtimestamp(): timestamp = time.time() print(timestamp)
millisecond_timestamp = int(round(time.time() * 1000)) return millisecond_timestamp
def generate_token(length=10): letters_and_digits = string.ascii_lowercase + string.digits return ''.join(random.choice(letters_and_digits) for i in range(length))
def is_valid_url(string): regex = re.compile( r'^(?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,})(?!\d)|' r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' r'(?::\d+)?' r'(?:/?|[/?]\S*)$', re.IGNORECASE) return regex.match(string) is not None
@app.route('/creat_redirect') def creat_redirect(): try: if request.headers.getlist("X-Forwarded-For"): ip = request.headers.getlist("X-Forwarded-For")[0] else: ip = request.remote_addr users_data_file = "data/users.json" redirect_data_file = "data/redirect_datas.json" address = request.args.get('address') token = request.args.get('token') with open(users_data_file, 'r') as file: users_data = json.load(file) if token in users_data: if is_valid_url(address) == True: user = users_data[token] address_token = generate_token(12) data = {address_token: [{"address":address, "timestamp":nowtimestamp(), "user_token":token, "ip":ip}]} with open(redirect_data_file, 'r') as file: old_redirect_data = json.load(file) combined_data = OrderedDict(data) combined_data.update(old_redirect_data)
with open(redirect_data_file, 'w') as f: json.dump(combined_data, f, indent=4) state = {"code":0, "address":f"https://127.0.0.1/redirect?address_token={address_token}", "timestamp":nowtimestamp()} return json.dumps(state) else: state = {"code":1, "error_message":"address error", "timestamp":nowtimestamp()} return json.dumps(state) else: state = {"code":1, "error_message":"token error", "timestamp":nowtimestamp()} return json.dumps(state) except Exception as e: error_code = generate_token(10) logging.error(f"{error_code},{nowtimestamp()}An error occurred: %s", e) state = {"code":1, "error":error_code, "timestamp":nowtimestamp()} return json.dumps(state)
@app.route('/redirect') def redirecturl(): redirect_data_file = "data/redirect_datas.json" address_token = request.args.get('address_token') with open(redirect_data_file, 'r') as file: redirect_data = json.load(file) if address_token in redirect_data: address = redirect_data[address_token][0]["address"] return redirect(str(address)) else: return "该重定向不存在"
if __name__ == '__main__': app.run(debug=True, port=8823)
|