我正在使用django和芹菜(django-celery)开展一个项目.我们的团队决定将所有数据访问代码(app-name)/manager.py包装在内(不要像管理员那样包装django),让(app-name)/task.py中的代码只处理汇编和执行芹菜任务(所以我们没有django此层中的ORM依赖项).
在我manager.py,我有这样的事情:
def get_tag(tag_name):
ctype = ContentType.objects.get_for_model(Photo)
try:
tag = Tag.objects.get(name=tag_name)
except ObjectDoesNotExist:
return Tag.objects.none()
return tag
def get_tagged_photos(tag):
ctype = ContentType.objects.get_for_model(Photo)
return TaggedItem.objects.filter(content_type__pk=ctype.pk, tag__pk=tag.pk)
def get_tagged_photos_count(tag):
return get_tagged_photos(tag).count()
Run Code Online (Sandbox Code Playgroud)
在我的task.py中,我喜欢将它们包装成任务(然后可能使用这些任务来完成更复杂的任务),所以我写这个装饰器:
import manager #the module within same app containing data access functions
class mfunc_to_task(object):
def __init__(mfunc_type='get'):
self.mfunc_type = mfunc_type
def __call__(self, f):
def wrapper_f(*args, **kwargs):
callback = kwargs.pop('callback', None)
mfunc = getattr(manager, f.__name__)
result = mfunc(*args, **kwargs)
if callback:
if self.mfunc_type == 'get':
subtask(callback).delay(result)
elif …Run Code Online (Sandbox Code Playgroud) 我试图按照RedditStyleVoting指令将django-voting集成到我的项目中.
在我的urls.py中,我做了类似这样的事情:
url(r'^sections/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
vote_on_object,
dict(
model=Section,
template_object_name='section',
template_name='script/section_confirm_vote.html',
allow_xmlhttprequest=True
),
name="section_vote",
Run Code Online (Sandbox Code Playgroud)
然后,在我的模板中:
{% vote_by_user user on section as vote %}
{% score_for_object section as score %}
<form class="sectionvote" id="sectionup{{ section.id }}"{% if vote and vote.is_upvote %} action="{% url section_vote object_id=section.id, direction="clear" %}"{% else %} action="{% url section_vote object_id=section.id, direction="up" %}"{% endif %} method="POST">
<input type="image" id="sectionuparrow{{ section.id }}" src="{{ MEDIA_URL }}/aup{% if vote and vote.is_upvote %}mod{% else %}grey{% endif %}.png"></form>
{{ score.score|default:0 }}
<form class="sectionvote" id="sectiondown{{ section.id }}"{% …Run Code Online (Sandbox Code Playgroud) 这看起来很简单,但我不知道我错了什么.
d1 = dict(zip(range(10), [[]]*10))
l1 = zip(range(10), range(10,20))
for pair in l1:
d1[pair[0]].append(pair)
Run Code Online (Sandbox Code Playgroud)
结果d1:
>>> d1
{0: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 1: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], 2: [(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (6, 16), (7, 17), (8, 18), (9, 19)], …Run Code Online (Sandbox Code Playgroud)