是否可以阻止 View 中的代码被所有访问该 View 的用户执行,而该代码正由单个用户执行?一种单线程 View 。
我需要它,因为我在此 View 中使用 pyinstaller
生成了 python 可执行文件,并通过配置文件将用户名传递给可执行文件。
例如:
class CliConfig(APIView):
def get(self, request, format=None):
try:
config['DEFAULT']['username'] = request.user
#make a build with pyinstaller
bin_file = open(*generated filepath *, 'rb')
response = Response(FileWrapper(bin_file), content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename="%s"' % '*filename*'
return response
finally:
config['DEFAULT']['username'] = ''
所以,基本上我想要的是在 django rest framwork APIView
中生成一个 python 可执行文件,它将有一个唯一的用户名它的设置。除了通过设置文件传递用户名外,我看不到其他方法。如果有办法 - 将不胜感激。
python 3.6.5
, djangorestframework==3.8.2
, pyinstaller==3.3.1
最佳答案
为什么要在配置中存储用户名? 这一代不应该是每个用户吗?
无论如何,在 View 中执行耗时的任务不是好的做法。
使用 Celery对于将生成可执行文件并在不停止 Django 的情况下接受任何变量的长期任务。在这个任务结束时Celery可以将可执行文件发送到电子邮件或其他东西。
from celery import Celery
app = Celery('hello', broker='amqp://guest@localhost//')
@app.task
def generate_executable(username):
# make a build with pyinstaller with username
bin_file = open(*generated filepath *, 'rb')
response = Response(FileWrapper(bin_file), content_type='application/octet-stream')
response['Content-Disposition'] = 'attachment; filename="%s"' % '*filename*'
# send email and/or returns as task result
return response
class CliConfig(APIView):
def get(self, request, format=None):
task = generate_executable(request.user)
task.delay()
return Response({"status": "started", "task_id": task.task_id})
关于python - django rest 单线程/阻塞 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407382/