python - django rest 单线程/阻塞 View

标签 python django python-3.x django-rest-framework pyinstaller

是否可以阻止 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/

相关文章:

python - 如何使用 Scrapy 抓取下一页

c# - 构建平衡的二叉搜索树

python - 合并排序查询集 - django

python - 在 CPanel 中使用 Python 在 Django 管理面板中加载静态文件

python - (discord.py) 如何让我的机器人随机回复 DM?

python - 限制数组上的 scipy.integrate.quad

python - 记忆化问题 - 房屋强盗问题

python - django 部署到 Heroku : Server Error(500)

python input() 在调用 input() 之前采用旧的标准输入

python - 为什么角色类和animation_dir上有一个AttributeError报告,尽管它已经明确定义了?