sla*_*acy 23 python mysql django multithreading django-models
我是Django的新手,但我想到的应用程序最终可能会出现如下所示的URL:
http://mysite/compare/id_1/id_2
Run Code Online (Sandbox Code Playgroud)
其中"id_1"和"id_2"是两个不同的Model对象的标识符.在"比较"的处理程序中,我想异步,并行地查询和检索对象id_1和id_2.
有没有办法使用标准的Django语法?我希望伪代码最终看起来像这样:
import django.async
# Issue the model query, but set it up asynchronously.
# The next 2 lines don't actually touch my database
o1 = Object(id=id_1).async_fetch()
o2 = Object(id=id_2).async_fetch()
# Now that I know what I want to query, fire off a fetch to do them all
# in parallel, and wait for all queries to finish before proceeding.
async.Execute((o2,o2))
# Now the code can use data from o1 and o2 below...
Run Code Online (Sandbox Code Playgroud)
Jar*_*die 11
没有像你所描述的那样严格的异步操作,但我认为你可以通过使用django的in_bulk查询运算符来实现相同的效果,该运算符需要一个id列表来查询.
对于这样的事情urls.py:
urlpatterns = patterns('',
(r'^compare/(\d+)/(\d+)/$', 'my.compareview'),
)
Run Code Online (Sandbox Code Playgroud)
这对于观点:
def compareview(request, id1, id2):
# in_bulk returns a dict: { obj_id1: <MyModel instance>,
# obj_id2: <MyModel instance> }
# the SQL pulls all at once, rather than sequentially... arguably
# better than async as it pulls in one DB hit, rather than two
# happening at the same time
comparables = MyModel.objects.in_bulk([id1, id2])
o1, o2 = (comparables.get(id1), comparables.get(id2))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4146 次 |
| 最近记录: |