views.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. from django.shortcuts import render
  2. # Create your views here.
  3. # views.py
  4. from rest_framework import generics
  5. from rest_framework.authentication import TokenAuthentication
  6. from .models import RedTourismSpot
  7. from .serializers import RedTourismSpotSerializer
  8. from django.db.models import Q
  9. from rest_framework import generics, mixins
  10. class RedSpotSearchAPIView(mixins.ListModelMixin, generics.GenericAPIView):
  11. pagination_class = None
  12. serializer_class = RedTourismSpotSerializer
  13. queryset = RedTourismSpot.objects.all()
  14. def get_queryset(self):
  15. queryset = super().get_queryset()
  16. search_term = self.request.query_params.get('q', None)
  17. if search_term=='undefined':
  18. search_term = None
  19. category = self.request.query_params.get('category', '').strip()
  20. print(f"接收参数 - 搜索词: {search_term} (类型: {type(search_term)}), 分类: '{category}'")
  21. print(f"初始查询集数量: {queryset.count()}")
  22. # 搜索逻辑
  23. if search_term != None:
  24. print("检测到q参数存在")
  25. search_term = search_term.strip()
  26. if search_term:
  27. print(f"应用搜索筛选,关键词: '{search_term}'")
  28. queryset = queryset.filter(
  29. Q(name__icontains=search_term) |
  30. Q(location__icontains=search_term) |
  31. Q(description__icontains=search_term)
  32. ).distinct()
  33. else:
  34. print("q参数为空字符串,不应用搜索筛选")
  35. else:
  36. print("未接收到q参数,不应用搜索筛选")
  37. # 分类逻辑
  38. if category:
  39. print(f"应用分类筛选: '{category}'")
  40. queryset = queryset.filter(category__iexact=category)
  41. print(f"最终查询集数量: {queryset.count()}")
  42. return queryset
  43. def get(self, request, *args, **kwargs):
  44. return self.list(request, *args, **kwargs)
  45. from rest_framework.views import APIView
  46. from rest_framework.response import Response
  47. from rest_framework import status
  48. from api.models import UserPlan, UserInfo
  49. from .serializers import UserPlanSerializer
  50. import logging
  51. logger = logging.getLogger(__name__)
  52. class AddToPlanView(APIView):
  53. # 移除了Token认证
  54. authentication_classes = []
  55. permission_classes = []
  56. def post(self, request, *args, **kwargs):
  57. logger.info(f"收到添加行程请求,数据: {request.data}")
  58. try:
  59. # 从请求数据中获取用户ID
  60. user_id = request.data.get('user_id')
  61. if not user_id:
  62. return Response(
  63. {'success': False, 'message': '缺少用户ID'},
  64. status=status.HTTP_400_BAD_REQUEST
  65. )
  66. # 验证用户是否存在
  67. try:
  68. user = UserInfo.objects.get(id=user_id)
  69. except UserInfo.DoesNotExist:
  70. return Response(
  71. {'success': False, 'message': '用户不存在'},
  72. status=status.HTTP_404_NOT_FOUND
  73. )
  74. # 处理请求数据
  75. serializer = UserPlanSerializer(data=request.data)
  76. if not serializer.is_valid():
  77. return Response(
  78. {'success': False, 'message': '数据验证失败', 'errors': serializer.errors},
  79. status=status.HTTP_400_BAD_REQUEST
  80. )
  81. spot_id = serializer.validated_data['spot_id']
  82. # 检查是否已存在
  83. if UserPlan.objects.filter(user=user, spot_id=spot_id).exists():
  84. return Response(
  85. {'success': False, 'message': '该景点已在您的行程中'},
  86. status=status.HTTP_400_BAD_REQUEST
  87. )
  88. # 保存时关联用户
  89. instance = serializer.save(user=user)
  90. return Response(
  91. {'success': True, 'data': UserPlanSerializer(instance).data},
  92. status=status.HTTP_201_CREATED
  93. )
  94. except Exception as e:
  95. logger.exception("添加行程时发生异常:")
  96. return Response(
  97. {'success': False, 'message': '服务器内部错误'},
  98. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  99. )
  100. from rest_framework.views import APIView
  101. from rest_framework.response import Response
  102. from rest_framework import status
  103. from api.models import UserPlan
  104. from .serializers import UserPlanSerializer
  105. from rest_framework.views import APIView
  106. from rest_framework.response import Response
  107. from rest_framework import status
  108. from .serializers import UserPlanSerializer
  109. class UserPlansView(APIView):
  110. def get(self, request, user_id, format=None): # 添加 format 参数
  111. try:
  112. # 检查用户是否存在(如果需要)
  113. # if not User.objects.filter(id=user_id).exists():
  114. # return Response(
  115. # {'success': False, 'message': '用户不存在'},
  116. # status=status.HTTP_404_NOT_FOUND
  117. # )
  118. plans = UserPlan.objects.filter(user_id=user_id).order_by('-created_at')
  119. if not plans.exists():
  120. return Response(
  121. {'success': True, 'data': [], 'message': '该用户暂无行程'},
  122. status=status.HTTP_200_OK
  123. )
  124. serializer = UserPlanSerializer(plans, many=True)
  125. return Response({
  126. 'success': True,
  127. 'data': serializer.data
  128. })
  129. except Exception as e:
  130. return Response({
  131. 'success': False,
  132. 'message': str(e)
  133. }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
  134. from rest_framework.views import APIView
  135. from rest_framework.response import Response
  136. from rest_framework import status
  137. from rest_framework.views import APIView
  138. from rest_framework.response import Response
  139. from rest_framework import status
  140. from api.models import UserPlan
  141. class DeletePlanView(APIView):
  142. # 移除认证类(不需要 Token)
  143. authentication_classes = [] # 禁用所有认证
  144. permission_classes = [] # 禁用所有权限检查
  145. def post(self, request, plan_id, *args, **kwargs):
  146. try:
  147. plan = UserPlan.objects.get(id=plan_id)
  148. plan.delete()
  149. return Response(
  150. {'success': True, 'message': '删除成功'},
  151. status=status.HTTP_200_OK
  152. )
  153. except UserPlan.DoesNotExist:
  154. return Response(
  155. {'success': False, 'message': '计划不存在'},
  156. status=status.HTTP_404_NOT_FOUND
  157. )
  158. except Exception as e:
  159. return Response(
  160. {'success': False, 'message': '服务器错误: ' + str(e)},
  161. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  162. )
  163. from django.shortcuts import render
  164. from rest_framework.views import APIView
  165. from rest_framework.response import Response
  166. from django.http import JsonResponse
  167. from rest_framework import status
  168. # coding: utf-8
  169. import _thread as thread
  170. import os
  171. import time
  172. import base64
  173. import datetime
  174. import hashlib
  175. import hmac
  176. import json
  177. from urllib.parse import urlparse
  178. import ssl
  179. from datetime import datetime
  180. from time import mktime
  181. from urllib.parse import urlencode
  182. from wsgiref.handlers import format_date_time
  183. import websocket
  184. import openpyxl
  185. from concurrent.futures import ThreadPoolExecutor, as_completed
  186. import os
  187. class Ws_Param(object):
  188. # 初始化
  189. def __init__(self, APPID, APIKey, APISecret, gpt_url):
  190. self.APPID = APPID
  191. self.APIKey = APIKey
  192. self.APISecret = APISecret
  193. self.host = urlparse(gpt_url).netloc
  194. self.path = urlparse(gpt_url).path
  195. self.gpt_url = gpt_url
  196. # 生成url
  197. def create_url(self):
  198. # 生成RFC1123格式的时间戳
  199. now = datetime.now()
  200. date = format_date_time(mktime(now.timetuple()))
  201. # 拼接字符串
  202. signature_origin = "host: " + self.host + "\n"
  203. signature_origin += "date: " + date + "\n"
  204. signature_origin += "GET " + self.path + " HTTP/1.1"
  205. # 进行hmac-sha256进行加密
  206. signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
  207. digestmod=hashlib.sha256).digest()
  208. signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
  209. authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
  210. authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
  211. # 将请求的鉴权参数组合为字典
  212. v = {
  213. "authorization": authorization,
  214. "date": date,
  215. "host": self.host
  216. }
  217. # 拼接鉴权参数,生成url
  218. url = self.gpt_url + '?' + urlencode(v)
  219. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  220. return url
  221. # 收到websocket错误的处理
  222. def on_error(ws, error):
  223. print("### error:", error)
  224. # 收到websocket关闭的处理
  225. def on_close(ws):
  226. print("### closed ###")
  227. # 收到websocket连接建立的处理
  228. def on_open(ws):
  229. thread.start_new_thread(run, (ws,))
  230. def run(ws, *args):
  231. data = json.dumps(gen_params(appid=ws.appid, query=ws.query, domain=ws.domain))
  232. ws.send(data)
  233. # 定义一个全局变量来存储content
  234. content_all = ""
  235. # 收到websocket消息的处理
  236. def on_message(ws, message):
  237. global content_all
  238. data = json.loads(message)
  239. code = data['header']['code']
  240. if code != 0:
  241. print(f'请求错误: {code}, {data}')
  242. ws.close()
  243. else:
  244. choices = data["payload"]["choices"]
  245. status = choices["status"]
  246. content = choices["text"][0]["content"]
  247. content_all += content
  248. print(content, end='')
  249. if status == 2:
  250. ws.close()
  251. def gen_params(appid, query, domain):
  252. """
  253. 通过appid和用户的提问来生成请参数
  254. """
  255. data = {
  256. "header": {
  257. "app_id": "6d30de8d",
  258. "uid": "1234",
  259. # "patch_id": [] #接入微调模型,对应服务发布后的resourceid
  260. },
  261. "parameter": {
  262. "chat": {
  263. "domain": domain,
  264. "temperature": 0.5,
  265. "max_tokens": 4096,
  266. "auditing": "default",
  267. }
  268. },
  269. "payload": {
  270. "message": {
  271. "text": [{"role": "user", "content": query}]
  272. }
  273. }
  274. }
  275. return data
  276. def main(appid, api_secret, api_key, Spark_url, domain, query):
  277. wsParam = Ws_Param(appid, api_key, api_secret, Spark_url)
  278. websocket.enableTrace(False)
  279. wsUrl = wsParam.create_url()
  280. ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)
  281. ws.appid = appid
  282. ws.query = query
  283. ws.domain = domain
  284. ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
  285. from django.utils import timezone
  286. class AITravelPlanView(APIView):
  287. def post(self, request):
  288. try:
  289. data = request.data
  290. # 参数验证
  291. locations = data.get('locations', [])
  292. days = data.get('days', 3)
  293. budget = data.get('budget', 5000)
  294. preferences = data.get('preferences', [])
  295. if not locations:
  296. return Response(
  297. {'status': 'error', 'error': '至少需要选择一个地点'},
  298. status=status.HTTP_400_BAD_REQUEST
  299. )
  300. # 构建AI提示词
  301. prompt = f"""你是一位资深旅游规划师,请为以下需求生成专业旅行计划:
  302. **基本需求**
  303. 地点:{", ".join(locations)}
  304. 天数:{days}天
  305. 预算:{budget}元
  306. 偏好:{", ".join(preferences) if preferences else "标准"}
  307. **输出要求**
  308. 1. 每日详细行程(时间+地点+活动)
  309. 2. 交通建议(含费用估算)
  310. 3. 餐饮推荐(人均消费)
  311. 4. 住宿建议(符合预算)
  312. 5. 舒适旅行贴士
  313. 6. 注意事项
  314. 格式要求:使用Markdown语法,清晰分段"""
  315. # 调用AI接口
  316. try:
  317. # 重置全局变量
  318. global content_all
  319. content_all = ""
  320. main(
  321. appid="6d30de8d",
  322. api_secret="YjMwN2E2YWE3MzU2NGE2YjI5ZDM5ZTMz",
  323. api_key="a88b5e5be130e0b91fdada536c36ac24",
  324. Spark_url="wss://spark-api.xf-yun.com/v4.0/chat",
  325. domain="4.0Ultra",
  326. query=prompt # 传入构建好的提示词
  327. )
  328. # 使用全局变量获取AI响应
  329. ai_response = content_all
  330. if not ai_response:
  331. raise ValueError("AI未返回有效内容")
  332. return Response({
  333. 'status': 'success',
  334. 'data': {
  335. 'recommendation': ai_response,
  336. }
  337. })
  338. except Exception as ai_error:
  339. return Response(
  340. {'status': 'error', 'error': f'AI服务异常: {str(ai_error)}'},
  341. status=status.HTTP_503_SERVICE_UNAVAILABLE
  342. )
  343. except Exception as e:
  344. return Response(
  345. {'status': 'error', 'error': f'服务器错误: {str(e)}'},
  346. status=status.HTTP_500_INTERNAL_SERVER_ERROR
  347. )