FormsAuthentication.Authenticate()方法总是返回false的原因

本文介绍了ASP.NET中两种主要的身份验证方法:FormsAuthentication.Authenticate()用于验证存储在Web.config文件中的用户名和密码;Membership.ValidateUser则用于验证存储在ASP.NET成员资格数据库中的密码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FormsAuthentication.Authenticate()方法要验证的用户名和密码必须存储在Web.config文件内。
如果要验证存储在“ASP.NET成员资格数据库”中的密码,则需要调用Membership.ValidateUser方法。

import os import time import cv2 import numpy as np import base64 import json import threading from .page_4_1_auto_set import image_detect from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import PasswordResetForm from django.contrib.auth.tokens import default_token_generator from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.core.mail import send_mail from django.contrib.auth.models import User from .models import UserInfo from ultralytics import YOLO from django.forms import Form, FileField from django.contrib.auth.forms import AuthenticationForm from django.http import JsonResponse, StreamingHttpResponse class VideoUploadForm(Form): video = FileField() def wechat_login(request): code = request.GET.get('code') if code: # 获取 access_token url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={settings.WECHAT_APPID}&secret={settings.WECHAT_SECRET}&code={code}&grant_type=authorization_code' import requests response = requests.get(url) data = response.json() if 'access_token' in data: access_token = data['access_token'] openid = data['openid'] # 获取用户信息 user_info_url = f'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}' user_info_response = requests.get(user_info_url) user_info = user_info_response.json() # 处理用户信息,例如创建或登录用户 # ... return redirect('home') else: # 重定向到微信授权页面 authorize_url = f'https://open.weixin.qq.com/connect/oauth2/authorize?appid={settings.WECHAT_APPID}&redirect_uri={settings.WECHAT_REDIRECT_URI}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' return redirect(authorize_url) def register(request): if request.method == 'POST': username = request.POST.get('username') email = request.POST.get('email') password1 = request.POST.get('password1') password2 = request.POST.get('password2') # 检查用户名是否已存在 if UserInfo.objects.filter(user__username=username).exists(): messages.error(request, '用户名已注册,请选择其他用户名!') return render(request, 'register.html', { 'username': username, 'email': email, 'error': 'username_exists' }, status=400) # 检查用户名长度 if len(username) < 3: messages.error(request, '用户名至少3个字符!') return render(request, 'register.html', { 'username': username, 'email': email, 'error': 'username_short' }, status=400) # 检查邮箱是否已存在 if UserInfo.objects.filter(email=email).exists(): messages.error(request, '邮箱已注册,请使用其他邮箱!') return render(request, 'register.html', { 'username': username, 'email': email, 'error': 'email_exists' }, status=400) # 检查邮箱格式 import re if not re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', email): messages.error(request, '请输入有效的邮箱地址!') return render(request, 'register.html', { 'username': username, 'email': email, 'error': 'email_invalid' }, status=400) # 检查密码复杂度 special_char_regex = re.compile(r'[!@#$%^&*(),.?":{}|<>]') if len(password1) < 8 or not special_char_regex.search(password1): messages.error(request, '密码长度至少为8个字符,且必须包含特殊字符!') return render(request, 'register.html', { 'username': username, 'email': email, 'error': 'password_weak' }, status=400) # 创建新用户 try: user = User.objects.create_user(username=username, email=email, password=password1) UserInfo.objects.create(user=user, email=email) messages.success(request, '注册成功!') return redirect('login') except Exception as e: messages.error(request, f'注册失败:{str(e)}') return render(request, 'register.html', status=500) return render(request, 'register.html') import logging logger = logging.getLogger(__name__) def user_login(request): if request.method == 'POST': form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) next_url = request.GET.get('next') if next_url: return redirect(next_url) return redirect('home') else: logger.error(f"认证失败,用户名: {username}") messages.error(request, '用户名或密码错误,请重试。') else: form = AuthenticationForm() return render(request, 'login.html', {'form': form}) @login_required def user_logout(request): logout(request) messages.success(request, '您已成功退出登录。') return redirect('login') def check_username(request): username = request.GET.get('username') exists = UserInfo.objects.filter(user__username=username).exists() return JsonResponse({ 'exists': exists, 'valid': len(username) >= 3 if username else False }) def check_email(request): email = request.GET.get('email') exists = UserInfo.objects.filter(email=email).exists() import re return JsonResponse({ 'exists': exists, 'valid': bool(re.match(r'^[^\s@]+@[^\s@]+\.[^\s@]+$', email)) if email else False }) def password_reset(request): if request.method == 'POST': form = PasswordResetForm(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') try: user = User.objects.get(email=email) # 生成重置密码的 token 和 uid token = default_token_generator.make_token(user) uid = urlsafe_base64_encode(force_bytes(user.pk)) # 构建重置密码的链接 from django.urls import reverse reset_url = request.build_absolute_uri(reverse('password_reset_confirm', args=[uid, token])) # 发送重置密码的邮件 send_mail( '重置密码', f'请点击以下链接重置您的密码:{reset_url}', settings.EMAIL_HOST_USER, [email], fail_silently=False, ) messages.success(request, '重置密码的邮件已发送,请检查您的邮箱。') return redirect('login') except User.DoesNotExist: messages.error(request, '该邮箱未注册。') else: form = PasswordResetForm() return render(request, 'password_reset.html', {'form': form}) def password_reset_confirm(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and default_token_generator.check_token(user, token): if request.method == 'POST': new_password1 = request.POST.get('new_password1') new_password2 = request.POST.get('new_password2') if new_password1 == new_password2: user.set_password(new_password1) user.save() messages.success(request, '密码重置成功,请使用新密码登录。') return redirect('login') else: messages.error(request, '两次输入的密码不一致,请重新输入。') return render(request, 'password_reset_confirm.html', {'uidb64': uidb64, 'token': token}) else: messages.error(request, '重置密码链接无效,请重新申请。') return redirect('password_reset') # @login_required def home(request): return render(request, 'home.html', {}) # @login_required def show_data_html(request): return render(request, 'show_data.html', {}) # @login_required def user_html(request): return render(request, 'user.html', {}) # @login_required def test_html(request): return render(request, 'test.html', {}) # @login_required def detection_html(request): return render(request, 'detection.html', {}) # @login_required def detection_CB_html(request): return render(request, 'detection_CB.html', {}) # @login_required def detection_video_html(request): return render(request, 'detection_video.html', {}) # @login_required def sjdsjksjskfs_html(request): return render(request, 'sjdsjksjskfs.html', {}) # @login_required def upload_video(request): if request.method == 'POST': try: video_file = request.FILES.get('video') video_id = request.POST.get('video_id') if not video_file or not video_id: return JsonResponse({'status': 'error', 'message': '缺少参数'}) # 确保临时目录存在 temp_dir = os.path.join(settings.BASE_DIR, 'temp', 'videos') if not os.path.exists(temp_dir): os.makedirs(temp_dir) # 保存视频文件 video_path = os.path.join(temp_dir, f"{video_id}.mp4") with open(video_path, 'wb+') as destination: for chunk in video_file.chunks(): destination.write(chunk) return JsonResponse({'status': 'success', 'video_id': video_id}) except Exception as e: return JsonResponse({'status': 'error', 'message': str(e)}) return JsonResponse({'status': 'error', 'message': '无效请求'}, status=405) @csrf_exempt def detect_video(request): if request.method == 'POST': # 获取视频文件 video_file = request.FILES.get('video') if video_file: # 保存视频文件到临时目录 video_path = os.path.join('temp', video_file.name) with open(video_path, 'wb+') as destination: for chunk in video_file.chunks(): destination.write(chunk) # 模型路径 model_path = os.path.join(settings.BASE_DIR, "Behaviewer/models/best.pt") # 输出视频路径 output_video_dir = os.path.join(settings.MEDIA_ROOT, 'videos') if not os.path.exists(output_video_dir): os.makedirs(output_video_dir) output_video_path = os.path.join(output_video_dir, video_file.name) # 调用函数进行视频目标检测 detect_objects_in_video(model_path, video_path, output_video_path, show=False) # 删除临时视频文件 os.remove(video_path) # 返回检测好的视频文件的路径 output_video_url = f'{settings.MEDIA_URL}videos/{os.path.basename(output_video_path)}' return JsonResponse({'success': True, 'output_video_url': output_video_url}) else: return JsonResponse({'success': False, 'message': '未找到视频文件'}) else: return JsonResponse({'success': False, 'message': '只支持POST请求'}) # 错步页面模型调用检测 def detect_objects_in_video(model_path, video_path, output_path=None, show=True): # 加载预训练模型 model = YOLO(model_path) # 打开视频文件 cap = cv2.VideoCapture(video_path) # 获取视频的帧率、宽度和高度 fps = cap.get(cv2.CAP_PROP_FPS) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 如果指定了输出路径,创建视频写入对象 if output_path: fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) frame_count = 0 total_time = 0 while cap.isOpened(): ret, frame = cap.read() if not ret: break # 记录开始时间 start_time = time.time() # 进行目标检测 results = model(frame) # 记录结束时间并累加耗时 end_time = time.time() total_time += end_time - start_time frame_count += 1 # 获取检测结果并绘制到帧上 annotated_frame = results[0].plot() # 计算并显示FPS fps_current = 1 / (end_time - start_time) cv2.putText(annotated_frame, f"FPS: {fps_current:.2f}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # 保存帧到输出视频 if output_path: out.write(annotated_frame) # 显示结果 if show: cv2.imshow("Object Detection", annotated_frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # 释放资源 cap.release() if output_path: out.release() cv2.destroyAllWindows() # 计算平均FPS if frame_count > 0: avg_fps = frame_count / total_time print(f"处理完成! 平均FPS: {avg_fps:.2f}") print(f"总帧数: {frame_count}") print(f"总耗时: {total_time:.2f}秒") #模态框 #框选目标 #deepseek版 # @csrf_exempt # def detect_target(request): # if request.method == 'POST': # try: # # 获取POST数据 # data = json.loads(request.body) # image_data = data['image'] # roi_data = data['roi'] # # # 从Base64提取图像数据 # header, encoded = image_data.split(",", 1) # image_bytes = base64.b64decode(encoded) # nparr = np.frombuffer(image_bytes, np.uint8) # frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # # # 准备配置区域(根据ROI) # x, y, w, h = roi_data['x'], roi_data['y'], roi_data['width'], roi_data['height'] # points = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]] # # # 配置检测区域(格式要求与page_4_1_auto_set.py一致) # config_area_current = {'观察区1': [[points]]} # # # 调用检测算法(使用默认参数) # processed_frame, mean_value = image_detect( # frame, # config_area_current, # currentback=0, # 0=检测比背景暗的目标 # kernal_erode=1, # kernal_dilate=1, # kernal_erode_2=1, # min_area=1, # max_area=10000, # adjust_threshold=15 # ) # # # 将处理后的图像转换为Base64 # _, buffer = cv2.imencode('.jpg', processed_frame) # processed_image_base64 = base64.b64encode(buffer).decode('utf-8') # # return JsonResponse({ # 'success': True, # 'processed_image': processed_image_base64, # 'mean_value': mean_value # }) # except Exception as e: # return JsonResponse({ # 'success': False, # 'message': str(e) # }) # return JsonResponse({'success': False, 'message': 'Invalid request'}) @csrf_exempt def detect_target(request): if request.method == 'POST': try: # 获取POST数据 data = json.loads(request.body) image_data = data['image'] roi_data = data['roi'] params = data.get('params', {}) # 从Base64提取图像数据 header, encoded = image_data.split(",", 1) image_bytes = base64.b64decode(encoded) nparr = np.frombuffer(image_bytes, np.uint8) frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR) # 准备配置区域(根据ROI) x, y, w, h = roi_data['x'], roi_data['y'], roi_data['width'], roi_data['height'] points = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]] # 配置检测区域 config_area_current = {'观察区1': [[points]]} # 调用检测算法 processed_frame, mean_value = image_detect( frame, config_area_current, currentback=params.get('currentback', 0), kernal_erode=params.get('kernal_erode', 1), kernal_dilate=params.get('kernal_dilate', 1), kernal_erode_2=params.get('kernal_erode_2', 1), min_area=params.get('min_area', 1), max_area=params.get('max_area', 10000), adjust_threshold=params.get('adjust_threshold', 15) ) # 将处理后的图像转换为Base64 _, buffer = cv2.imencode('.jpg', processed_frame) processed_image_base64 = base64.b64encode(buffer).decode('utf-8') return JsonResponse({ 'success': True, 'processed_image': processed_image_base64, 'mean_value': mean_value }) except Exception as e: return JsonResponse({ 'success': False, 'message': str(e) }) return JsonResponse({'success': False, 'message': 'Invalid request'}) # 添加新的视频处理视图 @csrf_exempt def process_video_stream(request): if request.method == 'POST': try: data = json.loads(request.body) video_id = data['video_id'] roi_data = data['roi'] params = data.get('params', {}) # 获取视频路径 video_path = os.path.join(settings.BASE_DIR, 'temp', 'videos', f"{video_id}.mp4") if not os.path.exists(video_path): return JsonResponse({'success': False, 'message': 'Video file not found'}) # 准备ROI配置 x, y, w, h = roi_data['x'], roi_data['y'], roi_data['width'], roi_data['height'] points = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]] config_area = {'观察区': [[points]]} # 创建流式响应 response = StreamingHttpResponse( video_processing_generator(video_path, config_area, params), content_type='multipart/x-mixed-replace; boundary=frame' ) return response except Exception as e: return JsonResponse({'success': False, 'message': str(e)}) return JsonResponse({'success': False, 'message': 'Invalid request method'}) # 视频处理生成器 def video_processing_generator(video_path, config_area, params): cap = cv2.VideoCapture(video_path) # 获取视频信息 fps = cap.get(cv2.CAP_PROP_FPS) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) while cap.isOpened(): ret, frame = cap.read() if not ret: break # 处理当前帧 processed_frame, _ = image_detect( frame, config_area, currentback=params.get('currentback', 0), kernal_erode=params.get('kernal_erode', 1), kernal_dilate=params.get('kernal_dilate', 1), kernal_erode_2=params.get('kernal_erode_2', 1), min_area=params.get('min_area', 1), max_area=params.get('max_area', 10000), adjust_threshold=params.get('adjust_threshold', 15) ) # 转换为JPEG格式 _, buffer = cv2.imencode('.jpg', processed_frame) frame_data = buffer.tobytes() # 以MJPEG格式发送帧 yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_data + b'\r\n') cap.release() 报错2025-07-30 11:30:09,399 WARNING D:\anaconda\envs\All\lib\site-packages\django\http\response.py:517: builtins.Warning: StreamingHttpResponse must consume synchronous iterators in order to serve them asynchronously. Use an asynchronous iterator instead
最新发布
07-31
那么根据我的提供的代码帮我添加一下,在HTTP模式下登录成功,对该用户名添加cookie和httponly from utils import USER_FILE, UPLOAD_DIR, DOWNLOAD_DIR, load_users, save_user, check_user, check_user_md5 from bottle import Bottle, static_file, redirect, request, run, template, BaseRequest, response from bottle_auth import AuthPlugin import hashlib import os import ctypes import tarfile import tempfile from routes_en import setup_routes_en, cleanup_tar_files import threading import time USER_FILE = '/mnt/usrfs/webTest/user_auth.txt' UPLOAD_DIR = '/mnt/usrfs/upload' DOWNLOAD_DIR = '/mnt/usrfs/' BaseRequest.MEMFILE_MAX = 1024 * 1024 * 15 # 15MB # 5. 自定义 AuthPlugin,支持md5密码 class MD5AuthPlugin(AuthPlugin): def __init__(self, users): super().__init__(users) def check_auth(self, username, password): # password是明文,转md5后比对 pwd_md5 = hashlib.md5(password.encode()).hexdigest() return check_user_md5(username, pwd_md5) def require(self, f): def check_auth(*args, **kwargs): username = request.auth[0] if request.auth else None password = request.auth[1] if request.auth else None if not username or not password: response.headers['WWW-Authenticate'] = 'Basic realm=\"Login Required\"' response.status = 401 return "Authentication required" if not self.check_auth(username, password): response.headers['WWW-Authenticate'] = 'Basic realm=\"Login Required\"' response.status = 401 return "Authentication failed" return f(*args, **kwargs) return check_auth # 6. 创建 Bottle 应用 app = Bottle() users = load_users() auth = MD5AuthPlugin(users) app.install(auth) setup_routes_en(app,auth) # 启动清理线程 if __name__ == '__main__': # 如果没有用户文件,自动创建一个默认用户 if not os.path.exists(USER_FILE): save_user('root', 'root') # 使用最简单的配置 t = threading.Thread(target=cleanup_tar_files, daemon=True) t.start() app.run(host='0.0.0.0', port=80, debug=False, reloader=False)以上是main;from utils import USER_FILE, UPLOAD_DIR, DOWNLOAD_DIR, check_user from bottle import static_file, redirect, request, template, response from bottle import template from page_generators_en import get_basic_info_html_en, get_dev_status_html_en import tarfile import os import time from vtysh_cmd_send import VtyshCommandExecutor USER_FILE = '/mnt/usrfs/webTest/user_auth.txt' UPLOAD_DIR = '/mnt/usrfs/upload' DOWNLOAD_DIR = '/mnt/usrfs/' def setup_routes_en(app, auth): @app.route('/www/baseMsg_en.asp') def basic_info_www_en(): html = get_basic_info_html_en() return template('basic_info_en', basic_info_html_en=html) @app.route('/www/devStatus_en.asp') def dev_status_www_en(): html = get_dev_status_html_en() return template('dev_status_en', dev_status_html_en=html) @app.route('/www/ipaddr_en.asp') def ip_config_page(): return template('ip_address_en') @app.route('/api/execute_ip_config', method='POST') def execute_ip_config(): try: # 获取前端发送的配置 config = request.json # 验证配置 if not config or 'network' not in config: return {'success': False, 'error': 'Invalid configuration'} # 使用VtyshCommandExecutor执行配置 from vtysh_cmd_send import VtyshCommandExecutor executor = VtyshCommandExecutor("../bin/vtysh") result = executor.execute_config(config) return result except Exception as e: return {'success': False, 'error': str(e)} # def file_root_en(app): @app.route('/') def index(): return redirect('/www/index1/index_en.html') @app.route('/download_file/<path:path>') def download_file(path): print(f"DEBUG: 下载请求路径: {path}") # 调试信息 abs_file = os.path.abspath(os.path.join(DOWNLOAD_DIR, path)) print(f"DEBUG: 绝对文件路径: {abs_file}") # 调试信息 # 检查DOWNLOAD_DIR是否存在 if not os.path.exists(DOWNLOAD_DIR): print(f"DEBUG: DOWNLOAD_DIR不存在") # 调试信息 return "DOWNLOAD_DIR不存在" if not abs_file.startswith(os.path.abspath(DOWNLOAD_DIR)): print(f"DEBUG: 路径安全检查失败") # 调试信息 return "非法路径" # 检查文件或目录是否存在 if not os.path.exists(abs_file): print(f"DEBUG: 文件/目录不存在: {abs_file}") # 调试信息 return f"文件/目录不存在: {abs_file}" # 如果是目录,创建tar文件 if os.path.isdir(abs_file): print(f"DEBUG: 开始打包目录: {abs_file}")# 调试信息 try: # 在DOWNLOAD_DIR中创建tar文件,而不是临时目录 tar_filename = os.path.basename(abs_file) + '.tar' tar_path = os.path.join(DOWNLOAD_DIR, tar_filename) print(f"DEBUG: tar文件路径: {tar_path}") # 调试信息 # 创建tar文件 with tarfile.open(tar_path, 'w') as tar: tar.add(abs_file, arcname=os.path.basename(abs_file)) # 检查tar文件是否创建成功 if os.path.exists(tar_path): file_size = os.path.getsize(tar_path) print(f"DEBUG: tar文件创建成功,大小: {file_size} 字节") # 调试信息 else: print(f"DEBUG: tar文件创建失败") # 调试信息 return "tar文件创建失败" print(f"DEBUG: 目录打包完成: {tar_path}") # 调试信息 print(f"DEBUG: 下载文件名: {tar_filename}") # 调试信息 # 使用static_file返回tar文件 # 设置响应头 response.set_header('Content-Type', 'application/x-tar') response.set_header('Content-Disposition', f'attachment; filename=\"{tar_filename}\"') response.set_header('Content-Length', str(file_size)) response.set_header('Accept-Ranges', 'bytes') # 直接 return 生成器 return generate_with_timeout(tar_path, timeout=60) except Exception as e: print(f"DEBUG: 打包目录失败: {e}") # 调试信息 return f"打包目录失败: {e}" # 如果是文件,直接下载 if not os.path.isfile(abs_file): print(f"DEBUG: 不是普通文件: {abs_file}") # 调试信息 return f"不是普通文件: {abs_file}" # 检查文件权限 if not os.access(abs_file, os.R_OK): print(f"DEBUG: 文件没有读取权限: {abs_file}") # 调试信息 return f"文件没有读取权限: {abs_file}" print(f"DEBUG: 文件存在,开始下载: {abs_file}") # 调试信息 filename = os.path.basename(abs_file) print(f"DEBUG: 下载文件名: {filename}") # 调试信息 # 使用正确的MIME类型和文件名 return static_file(filename, root=os.path.dirname(abs_file), download=filename) @app.route('/<filepath:path>') def serve_static(filepath): return static_file(filepath, root='/mnt/usrfs/') # 表单登录 @app.route('/action/login', method='POST') def do_login(): username = request.forms.get('username') password = request.forms.get('password') if check_user(username, password): return redirect('/www/index_en.htm') else: return "Login failed!" # 受保护路由 @app.route('/protected') @auth.require def protected(): return "你已通过 HTTP Basic Auth 认证!" @app.route('/www/web_upload_file_en.asp', method=['GET', 'POST']) def web_upload_file_en(): if request.method == 'GET': return template('upload_en') # 注意这里是 upload._en else: upload_file = request.files.get('uploadfile') if not upload_file or not upload_file.filename: return "<p style='color:red'>没有选择文件!</p>" save_path = os.path.join(UPLOAD_DIR, upload_file.filename) upload_file.save(save_path, overwrite=True) return f"<p style='color:green'>文件已上传到: {save_path}</p><a href='/www/web_upload_file_en.asp'>返回</a>" @app.route('/filebrowser') @app.route('/filebrowser/<path:path>') def filebrowser(path=''): print(f"DEBUG: 访问路径: {path}") # 调试信息 abs_dir = os.path.abspath(os.path.join(DOWNLOAD_DIR, path)) print(f"DEBUG: 绝对路径: {abs_dir}") # 调试信息 if not abs_dir.startswith(os.path.abspath(DOWNLOAD_DIR)): print(f"DEBUG: 路径安全检查失败") # 调试信息 return "非法路径" if not os.path.isdir(abs_dir): print(f"DEBUG: 目录不存在: {abs_dir}") # 调试信息 return "目录不存在" items = [] for fname in sorted(os.listdir(abs_dir)): fpath = os.path.join(abs_dir, fname) is_dir = os.path.isdir(fpath) items.append({'name': fname, 'is_dir': is_dir}) parent = os.path.dirname(path) if path else None print(f"DEBUG: 父目录: {parent}") # 调试信息 return template('download_en', items=items, cur_path=path, parent=parent) def generate_with_timeout(file_path, timeout=60): start_time = time.time() with open(file_path, 'rb') as f: while True: if time.time() - start_time > timeout: break chunk = f.read(1024 * 1024) if not chunk: break yield chunk def cleanup_tar_files(): while True: now = time.time() for fname in os.listdir(DOWNLOAD_DIR): if fname.endswith('.tar'): fpath = os.path.join(DOWNLOAD_DIR, fname) try: if os.path.isfile(fpath): # 删除2分钟以前的tar文件 if now - os.path.getmtime(fpath) > 120: os.remove(fpath) print(f"DEBUG: 自动清理tar文件: {fpath}") except Exception as e: print(f"DEBUG: 清理tar文件失败: {e}") time.sleep(60) # 每分钟检查一次 以上是route部分
07-22
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值