Response_Code = 500 Error_Message = Internal Server Error

本文提供了一种解决方法,用于修复使用Selenium时出现的500内部服务器错误。通过调整Selenium初始化代码,可以有效地避免此类问题。
将代码修改如下可以解决Response_Code = 500 Error_Message = Internal Server Error:
selenium = new DefaultSelenium("localhost", port, browserString, url) {
public void open(String url) {
commandProcessor.doCommand("open", new String[] {url,"true"});
}
};
继续修改以下代码,目前企业微信@机器人无法实现重启子程序 import subprocess import threading import time import requests import json import logging import os import signal import psutil from flask import Flask, request, jsonify # 配置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.StreamHandler() ] ) logger = logging.getLogger("MainProgram") # 企业微信机器人配置 WECHAT_WEBHOOK = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=9ccdb6cc-5a44-4865-b442-7d7c184a6ccd" REQUEST_TIMEOUT = 10 # 网络请求超时时间(秒) # 全局状态 subprocess_proc = None subprocess_active = False last_error = None app = Flask(__name__) def send_wechat_alert(message): """通过企业微信机器人发送警报(带超时机制)""" headers = {"Content-Type": "application/json"} payload = { "msgtype": "text", "text": { "content": message, "mentioned_mobile_list": ["@all"] } } try: # 添加超时参数 response = requests.post( WECHAT_WEBHOOK, data=json.dumps(payload), headers=headers, timeout=REQUEST_TIMEOUT ) if response.status_code == 200: logger.info("企业微信警报发送成功") else: logger.error(f"企业微信发送失败: {response.status_code} - {response.text}") except requests.exceptions.Timeout: logger.error("企业微信请求超时") except requests.exceptions.RequestException as e: logger.error(f"发送企业微信警报时出错: {str(e)}") def start_subprogram(): """启动子程序(增强健壮性)""" global subprocess_proc, subprocess_active try: # 确保之前的进程已终止 if subprocess_proc and subprocess_proc.poll() is None: force_kill_process(subprocess_proc.pid) # 启动新进程 subprocess_proc = subprocess.Popen( ["python", "Generating Task Simulator.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, # 行缓冲 universal_newlines=True ) subprocess_active = True logger.info("子程序已启动") send_wechat_alert("🚀 子程序已成功启动") return True except Exception as e: logger.error(f"启动子程序失败: {str(e)}") send_wechat_alert(f"❌ 子程序启动失败: {str(e)}") return False def stop_subprogram(): """停止子程序(增强强制终止能力)""" global subprocess_proc, subprocess_active if subprocess_proc and subprocess_active: try: # 尝试优雅终止 subprocess_proc.terminate() # 等待最多5秒 try: subprocess_proc.wait(timeout=5) except subprocess.TimeoutExpired: logger.warning("子程序未响应终止信号,尝试强制终止") force_kill_process(subprocess_proc.pid) subprocess_active = False logger.info("子程序已停止") send_wechat_alert("🛑 子程序已停止") return True except Exception as e: logger.error(f"停止子程序失败: {str(e)}") send_wechat_alert(f"❌ 停止子程序失败: {str(e)}") return False return True def force_kill_process(pid): """强制终止进程及其所有子进程""" try: parent = psutil.Process(pid) children = parent.children(recursive=True) # 先终止子进程 for child in children: try: child.terminate() except psutil.NoSuchProcess: pass # 等待子进程终止 gone, alive = psutil.wait_procs(children, timeout=5) # 强制终止剩余进程 for p in alive: p.kill() # 终止主进程 try: parent.terminate() parent.wait(timeout=3) except psutil.NoSuchProcess: pass logger.info(f"已强制终止进程树 PID: {pid}") return True except Exception as e: logger.error(f"强制终止进程失败: {str(e)}") return False def monitor_subprocess(): """监控子程序状态和输出(增强健壮性)""" global last_error while True: try: if subprocess_proc and subprocess_active: # 检查子程序是否已退出 return_code = subprocess_proc.poll() if return_code is not None: logger.error(f"子程序意外退出,返回码: {return_code}") send_wechat_alert(f"⚠️ 子程序意外退出! 返回码: {return_code}") start_subprogram() # 自动重启 # 非阻塞读取错误输出 while True: line = subprocess_proc.stderr.readline().strip() if not line: break if "SUB_ERROR:" in line: error_msg = line.split("SUB_ERROR:")[1].strip() logger.error(f"检测到子程序错误: {error_msg}") if error_msg != last_error: # 避免重复发送相同错误 send_wechat_alert(f"🔥 子程序错误:\n{error_msg}") last_error = error_msg except Exception as e: logger.error(f"监控线程出错: {str(e)}") time.sleep(5) # 出错后等待 time.sleep(1) # 每秒检查一次 @app.route('/wechat', methods=['POST']) def wechat_command(): """接收企业微信机器人指令(带超时处理)""" try: data = request.json if not data: return jsonify({"error": "Invalid request"}), 400 command = data.get("text", "").strip().lower() user = data.get("from", {}).get("name", "未知用户") response_text = "" if "重启" in command: if stop_subprogram(): time.sleep(1) if start_subprogram(): response_text = f"{user} 已重启子程序 ✅" else: response_text = f"{user} 重启失败 ❌" else: response_text = f"{user} 重启失败 ❌" elif "停止" in command: if stop_subprogram(): response_text = f"{user} 已停止子程序 ⛔" else: response_text = f"{user} 停止子程序失败 ❌" elif "状态" in command: status = "运行中 ✅" if subprocess_active else "已停止 ⛔" last_error_info = f"\n最后错误: {last_error}" if last_error else "" response_text = f"子程序状态: {status}{last_error_info}" else: response_text = "可用命令: 重启, 停止, 状态" return jsonify({ "msgtype": "text", "text": {"content": response_text} }) except Exception as e: logger.error(f"处理微信命令时出错: {str(e)}") return jsonify({"error": "Internal server error"}), 500 if __name__ == "__main__": # 启动子程序 start_subprogram() # 启动监控线程 monitor_thread = threading.Thread(target=monitor_subprocess, daemon=True) monitor_thread.start() logger.info("主程序监控已启动") logger.info("Flask 指令服务器监听中...") # 启动Flask服务器(添加线程支持) app.run(host='0.0.0.0', port=5000, threaded=True)
08-07
#ifndef _SIP_PROTOCOL_H #define _SIP_PROTOCOL_H #include "common/sip_common.h" /* SIP方法定义 */ typedef enum sip_method { SIP_METHOD_INVITE = 0, SIP_METHOD_ACK, SIP_METHOD_BYE, SIP_METHOD_CANCEL, SIP_METHOD_REGISTER, SIP_METHOD_OPTIONS, SIP_METHOD_MAX }sip_method; /* SIP响应状态码 */ /* SIP响应状态码枚举 (RFC 3261及相关扩展) */ typedef enum sip_status_code { /* 1xx 临时响应 */ SIP_100_TRYING = 100, SIP_180_RINGING = 180, SIP_181_CALL_IS_BEING_FORWARDED = 181, SIP_182_QUEUED = 182, SIP_183_SESSION_PROGRESS = 183, /* 2xx 成功响应 */ SIP_200_OK = 200, SIP_202_ACCEPTED = 202, // RFC3265 /* 3xx 重定向响应 */ SIP_300_MULTIPLE_CHOICES = 300, SIP_301_MOVED_PERMANENTLY = 301, SIP_302_MOVED_TEMPORARILY = 302, SIP_305_USE_PROXY = 305, SIP_380_ALTERNATIVE_SERVICE = 380, /* 4xx 客户端错误 */ SIP_400_BAD_REQUEST = 400, SIP_401_UNAUTHORIZED = 401, SIP_402_PAYMENT_REQUIRED = 402, SIP_403_FORBIDDEN = 403, SIP_404_NOT_FOUND = 404, SIP_405_METHOD_NOT_ALLOWED = 405, SIP_406_NOT_ACCEPTABLE = 406, SIP_407_PROXY_AUTHENTICATION_REQUIRED = 407, SIP_408_REQUEST_TIMEOUT = 408, SIP_410_GONE = 410, SIP_413_REQUEST_ENTITY_TOO_LARGE = 413, SIP_414_REQUEST_URI_TOO_LONG = 414, SIP_415_UNSUPPORTED_MEDIA_TYPE = 415, SIP_416_UNSUPPORTED_URI_SCHEME = 416, SIP_420_BAD_EXTENSION = 420, SIP_421_EXTENSION_REQUIRED = 421, SIP_423_INTERVAL_TOO_BRIEF = 423, SIP_480_TEMPORARILY_UNAVAILABLE = 480, SIP_481_CALL_TRANSACTION_DOES_NOT_EXIST = 481, SIP_482_LOOP_DETECTED = 482, SIP_483_TOO_MANY_HOPS = 483, SIP_484_ADDRESS_INCOMPLETE = 484, SIP_485_AMBIGUOUS = 485, SIP_486_BUSY_HERE = 486, SIP_487_REQUEST_TERMINATED = 487, SIP_488_NOT_ACCEPTABLE_HERE = 488, SIP_489_BAD_EVENT = 489, // RFC3265 SIP_491_REQUEST_PENDING = 491, SIP_493_UNDECIPHERABLE = 493, /* 5xx 服务器错误 */ SIP_500_SERVER_INTERNAL_ERROR = 500, SIP_501_NOT_IMPLEMENTED = 501, SIP_502_BAD_GATEWAY = 502, SIP_503_SERVICE_UNAVAILABLE = 503, SIP_504_SERVER_TIME_OUT = 504, SIP_505_VERSION_NOT_SUPPORTED = 505, SIP_513_MESSAGE_TOO_LARGE = 513, /* 6xx 全局错误 */ SIP_600_BUSY_EVERYWHERE = 600, SIP_603_DECLINE = 603, SIP_604_DOES_NOT_EXIST_ANYWHERE = 604, SIP_606_NOT_ACCEPTABLE = 606 } sip_status_code; /* SIP URI结构 */ typedef struct sip_uri { char scheme[8]; /* "sip" or "sips" */ char user[32]; /* username */ char host[32]; /* domain or IP */ U16 port; /* port number */ char parameters[32]; /* URI parameters */ }sip_uri; /* SIP Via头结构 */ typedef struct sip_via { char protocol[16]; /* "SIP/2.0" */ char transport[8]; /* "UDP", "TCP" */ char host[64]; /* sent-by host */ U16 port; /* sent-by port */ char branch[32]; /* branch parameter */ char received[32]; /* received parameter */ U16 rport; /* rport parameter */ }sip_via; /* 认证信息结构体 */ typedef struct auth_info_t{ char realm[128]; char nonce[128]; char algorithm[32]; char qop[32]; char opaque[128]; int stale; char response[33]; } auth_info_t; /* SIP消息头结构 */ typedef struct sip_headers { struct sip_uri from; /* From header */ struct sip_uri to; /* To header */ struct sip_uri request_uri; /* Request-URI */ struct sip_via via; /* Via header */ char call_id[64]; /* Call-ID header */ U32 cseq; /* CSeq number */ enum sip_method cseq_method;/* CSeq method */ U8 max_forwards; /* Max-Forwards header */ char content_type[64]; /* Content-Type header */ char contact[64]; U32 content_length; /* Content-Length header */ U32 Expires; char user_agent[64]; /* User-Agent header */ auth_info_t auth; }sip_headers; /* SIP消息体结构 */ typedef struct sip_body { char *content; /* Message body content */ U32 length; /* Message body length */ char type[32]; /* Content type */ }sip_body; /* SIP消息结构 */ typedef struct sip_message { U8 type; /* 0: request, 1: response */ enum sip_method method;/* Method (for requests) */ U16 status_code; /* Status code (for responses) */ char reason_phrase[32];/* Reason phrase (for responses) */ struct sip_headers headers; /* SIP headers */ struct sip_body body; /* Message body */ char *raw_data; /* Raw message data */ U32 raw_length; /* Raw message length */ struct sockaddr_in source; /* Message source */ struct list_head list; /* List head for message queue */ }sip_message; /* SIP事务信息 */ typedef struct sip_transaction { char branch[32]; /* Transaction branch */ enum sip_method method; /* Transaction method */ U32 timeout; /* Transaction timeout */ unsigned long start_time; /* Start time in jiffies */ struct sip_message request; /* Original request */ struct sip_message last_response; /* Last response */ void *user_data; /* User-specific data */ U8 state; /*0,off,1 on*/ }sip_transaction; /* 协议栈配置 */ typedef struct sip_protocol_config { char user_agent[32]; U8 max_forwards; U32 t1_timeout; /* T1 timer (RTT estimate) */ U32 t2_timeout; /* T2 timer (64*T1) */ U32 t4_timeout; /* T4 timer (5000ms) */ }sip_protocol_config; /* SIP协议栈接口 */ int sip_message_parse(sip_message *msg, const char *data, U32 length); int sip_message_build(sip_message *msg, char *buffer, U32 size); void sip_message_free(sip_message *msg); // int sip_send_message(S32 sip_socket, struct sip_message *msg,const char *dest_addr, U16 dest_port); int sip_uri_parse(struct sip_uri *uri, const char *uri_str); int sip_uri_build(struct sip_uri *uri, char *buffer, U32 size); struct sip_transaction *sip_transaction_create(struct sip_message *ori_req); void sip_transaction_free(struct sip_transaction *trans); const char *sip_method_to_string(enum sip_method method); sip_method sip_string_to_method(const char *method_str); const char *sip_status_to_reason(U16 status_code); void sip_generate_branch(char *branch, U32 size); void sip_generate_tag(char *tag, U32 size); void sip_generate_call_id(char *buf, int len); #endif /* _SIP_PROTOCOL_H */ 为这段程序所有字符数组最大长度改为宏定义的最大长度
10-28
# products/views.py from django.shortcuts import render from rest_framework import viewsets, status from rest_framework.decorators import action, api_view from rest_framework.response import Response from .models import MinqingSpecialty, Recipe, CulturalTrivia from .serializers import MinqingSpecialtySerializer, RecipeSerializer import random from datetime import datetime import dashscope from django.conf import settings import os # ======================== # 特产与菜谱 ViewSet # ======================== class MinqingSpecialtyViewSet(viewsets.ModelViewSet): queryset = MinqingSpecialty.objects.all() serializer_class = MinqingSpecialtySerializer @action(detail=True, methods=['get']) def recipes(self, request, pk=None): """获取某个特产的所有菜谱""" specialty = self.get_object() recipes = Recipe.objects.filter(specialty=specialty) serializer = RecipeSerializer(recipes, many=True) return Response(serializer.data) @api_view(['GET']) def recipe_list(request, specialty_id): """获取某个特产的所有菜谱(独立接口)""" recipes = Recipe.objects.filter(specialty_id=specialty_id) serializer = RecipeSerializer(recipes, many=True) return Response(serializer.data) @api_view(['GET']) def daily_trivias(request): """获取每日三条冷知识(首页轮播)""" active_trivias = CulturalTrivia.objects.filter(is_active=True) if not active_trivias.exists(): return Response([], status=status.HTTP_200_OK) today = datetime.now().strftime('%Y%m%d') random.seed(today) selected = random.sample(list(active_trivias), min(3, len(active_trivias))) result = [ { 'icon': item.icon, 'category': item.category, 'content': item.content } for item in selected ] return Response(result) # ======================== # AI 对话接口(重点修复) # ======================== @api_view(['POST']) def chat_with_ai(request): """ 智能客服接口:接收用户问题,调用通义千问返回回答 请求格式:{"message": "大红袍和水仙有什么区别?"} 返回格式:{"reply": "..."} """ user_message = request.data.get('message', '').strip() if not user_message: return Response({"error": "问题不能为空"}, status=status.HTTP_400_BAD_REQUEST) # 获取 API Key api_key = os.getenv("DASHSCOPE_API_KEY") if not api_key: return Response( {"error": "API密钥未设置,请检查环境变量 DASHSCOPE_API_KEY"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) try: # ✅ 使用新版 messages 格式调用 qwen-plus response = dashscope.Generation.call( model='qwen-plus', messages=[ { 'role': 'system', 'content': '你是福建特色文化与非遗美食的专家助手,请用通俗易懂、亲切自然的语言回答问题。' '回答要结合历史、工艺、口感、民俗等角度,突出福建地域特色。' }, { 'role': 'user', 'content': user_message } ], api_key=api_key, # ✅ 推荐每次调用传入 api_key temperature=0.7, top_p=0.85, max_tokens=1024 ) # ✅ 检查状态码和输出 if response.status_code == 200: if response.output and 'choices' in response.output: ai_reply = response.output['choices'][0]['message']['content'].strip() return Response({"reply": ai_reply}) else: return Response({"error": "AI 返回内容为空"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: error_msg = response.message or "未知错误" return Response( {"error": f"AI 调用失败: {error_msg} (状态码: {response.status_code})"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) except Exception as e: # 捕获所有异常,避免崩溃 return Response( {"error": f"服务器内部错误: {str(e)}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR ) 没问题啊?
最新发布
11-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值