Django 中的协程

编程入门 行业动态 更新时间:2024-10-25 01:28:24
本文介绍了Django 中的协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

上下文:我正在编写一个 Django 脚本,如下所示.据我所知,下面的循环将阻止 Django 应用程序并阻止其他进程运行(例如请求处理程序).

Context: I am writing a Django script as shown below. To my knowledge, the loop below will block the Django app and prevent other processes from running(ex. request handlers).

问题:我该怎么做Django将运行下面的循环和yield 在其他脚本被触发时运行它们.当上述脚本完成后,循环将继续在同一索引上.

Problem: What should I do so Django will run the following loop and yield to run other scripts when they are triggered. When said scripts are completed, the loop will resume on the same index.

# ./app.py while True: items = queryItems() for item in items: process(item)

约束:答案应该适用于 Python 2.7 并且只使用支持 Python 2.7 的库.

Constraint: The answer should work in Python 2.7 and only uses libraries supporting Python 2.7.

推荐答案

一些事情:

据我所知,下面的循环将阻止 Django 应用程序并阻止其他进程运行(例如请求处理程序).

To my knowledge, the loop below will block the Django app and prevent other processes from running(ex. request handlers).

这是部分正确的;循环将阻止您的当前请求,直到它完成,但它不会阻止其他请求同时发生(来自其他客户端).传入的每个请求都将在单独的工作进程中执行.

This is partially true; the loop will block your current request until it has completed, however it won't block other requests from happening concurrently (from other clients). Each request that comes in will be executed in a separate worker process.

我应该怎么做 Django 将运行以下循环并在其他脚本被触发时让步运行.

What should I do so Django will run the following loop and yield to run other scripts when they are triggered.

我认为您在这里问的是我如何异步/并行运行 process(item)?".Django 没有提供任何可以像开箱即用的并行运行任务的东西.如果您想等到所有处理完成后再返回响应,您可以使用多线程/多进程方法.另一种选择是使用 celery,它是一个异步任务运行器,可以很好地插入 django.Celery 允许完全独立于请求/响应周期的任务执行,并具有许多用于检查任务状态等的不错功能.

I think what you're asking here is "how can I run process(item) asynchronously/in parallel?". Django doesn't come with anything that can run tasks in parallel like that out of the box. If you want to wait until all the processing has completed before returning a response, you could use a multithread/multiprocess approach. Another option is to use celery which is an asynchronous task runner that plugs nicely into django. Celery allows for task execution totally independent of the request/response cycle and has lots of nice features for checking the status of your tasks etc.

更多推荐

Django 中的协程

本文发布于:2023-11-23 10:01:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621034.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!