upload_apk.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import os
  2. from rest_framework.views import APIView
  3. from rest_framework.response import Response
  4. from rest_framework.parsers import FileUploadParser
  5. from kedong.settings import MEDIA_ROOT
  6. import time
  7. import uuid
  8. from datetime import datetime
  9. from django.conf import settings
  10. from smartfarming.models.agriculture import APKLogs
  11. from smartfarming.serializers.apk_serializers import APKLogsSerializers
  12. config = settings.CONFIG
  13. class NewUploadAPIView(APIView):
  14. # 上传apk文件
  15. def post(self, request):
  16. server_web = config.get("server_web")
  17. local_path = os.path.join(MEDIA_ROOT, "app")
  18. os.mkdir(local_path) if not os.path.exists(local_path) else None
  19. file_obj = request.data['file']
  20. if file_obj.size > 1024 * 1024 * 200:
  21. return Response({"code": 2, "msg": "请上传小于200M文件"})
  22. try:
  23. proxy_front = f'{server_web}/media/app'
  24. stamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
  25. file_name = "kedong." + ((file_obj.name).split("."))[-1]
  26. file = os.path.join(local_path, file_name)
  27. old_file_name = f"{str(stamp)}-{file_name}"
  28. real_url = os.path.join(local_path, old_file_name)
  29. if os.path.exists(file):
  30. os.rename(file, real_url)
  31. download_url = f"{proxy_front}/{old_file_name}"
  32. app = APKLogs.objects.all().order_by("-upltime")
  33. if app:
  34. app = app.first()
  35. app.history_apk = download_url
  36. app.save()
  37. with open(file, 'wb') as f:
  38. for chunk in file_obj.chunks():
  39. f.write(chunk)
  40. url = f'{proxy_front}/{file_name}'
  41. return Response({"url": url, "old_url": download_url, "code": 0, "msg": "success"})
  42. except Exception as e:
  43. return Response({"code": 2, "msg": "APK保存失败,请检查或重试"})
  44. class APKUploadView(APIView):
  45. # 保存app信息
  46. def post(self, request):
  47. try:
  48. request_data = request.data
  49. apk = request_data.get('apk')
  50. history_qr_code = request_data.get('history_qr_code')
  51. mark = request_data.get("mark")
  52. app = APKLogs()
  53. app.history_apk = apk if apk else ""
  54. app.history_qr_code = history_qr_code if history_qr_code else ""
  55. app.mark = mark if mark else ""
  56. app.upltime = int(time.time())
  57. app.save()
  58. return Response({"code": 0, "msg": "success"})
  59. except Exception as e:
  60. print(e)
  61. return Response({"code": 1, "msg": "保存失败"})
  62. class APPListAPIView(APIView):
  63. # app信息列表
  64. def post(self, request):
  65. queryset = APKLogs.objects.all().order_by("-upltime")
  66. serializers = APKLogsSerializers(queryset, many=True)
  67. return Response({"code": 0, "msg": "success", "data": serializers.data})