views.py 14 KB

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