小编arg*_*rgo的帖子

何时使用或不使用django ORM中的iterator()

这是来自queryset iterator()方法django文档:

QuerySet通常在内部缓存其结果,以便重复的计算不会导致其他查询.相反,iterator()将直接读取结果,而不在QuerySet级别执行任何缓存(在内部,默认迭代器调用iterator()并缓存返回值).对于返回大量只需要访问一次的大量对象的QuerySet,这可以带来更好的性能并显着降低内存.

阅读之后,我仍然感到困惑:关于性能提升和内存减少的一线表明我们应该使用这种iterator()方法.有人可以提供一些好的和坏的案例iterator()使用的例子吗?

即使查询结果没有被缓存,如果他们真的想多次访问模型,有人只能做以下事情吗?

saved_queries = list(Model.objects.all().iterator())
Run Code Online (Sandbox Code Playgroud)

python django orm iterator django-queryset

20
推荐指数
2
解决办法
2万
查看次数

Django - 如何实时跟踪用户是否在线/离线?

我正在考虑使用django-notifications和Web Sockets向iOS/Android和Web应用程序发送实时通知.所以我可能会使用Django频道.

我可以使用Django频道实时跟踪用户的在线状态吗?如果是,那么如何在不经常轮询服务器的情况下实现这一目标?

我正在寻找最佳实践,因为我找不到任何合适的解决方案.

更新:

我到目前为止尝试的是以下方法:使用Django Channels,我实现了一个WebSocket使用者,在连接时将用户状态设置为'online',而当套接字断开时,用户状态将被设置为'offline'.最初我想要包括'away'状态,但我的方法无法提供这种信息.此外,当用户使用来自多个设备的应用程序时,我的实现将无法正常工作,因为连接可以在设备上关闭,但仍然在另一个设备上打开; 'offline'即使用户有另一个打开的连接,状态也将设置为.

class MyConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        # Called when a new websocket connection is established
        print("connected", event)
        user = self.scope['user']
        self.update_user_status(user, 'online')

    async def websocket_receive(self, event):
        # Called when a message is received from the websocket
        # Method NOT used
        print("received", event)

    async def websocket_disconnect(self, event):
        # Called when a websocket is disconnected
        print("disconnected", event)
        user = self.scope['user'] …
Run Code Online (Sandbox Code Playgroud)

django django-notification django-channels

15
推荐指数
2
解决办法
2536
查看次数

kombu utils 对象 py line 42 in __ get __ return obj __ dict __[ self __ name __] keyerror data

设置.py

CELERY_BROKER_URL = 'redis://localhost:6379'
CELERY_RESULT_BACKEND = 'redis://localhost:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'
CELERY_TIMEZONE = 'Asia/Makassar'
# Other Celery settings
CELERY_BEAT_SCHEDULE = {
    'add_task': {
        'add_task': 'data_loader.tasks.add_task',
        'schedule': crontab(minute=55, hour=13),

    }
    # 'task-number-two': {
    #     'task': 'data_loader.tasks.demo',
    #     'schedule': crontab(minute=2, hour='18'),
    # }
}
Run Code Online (Sandbox Code Playgroud)

芹菜.py ...................

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'resolution_validator.settings')

app = Celery('resolution_validator')

# Using a string …
Run Code Online (Sandbox Code Playgroud)

django celery

8
推荐指数
1
解决办法
1841
查看次数

使用python-docx从.docx文件中提取图像位置

我正在尝试使用python-docx库从.docx文件中获取图像索引.我能够提取图像的名称,图像的高度和宽度.但不是它在word文件中的索引

import docx
doc = docx.Document(filename)
for s in doc.inline_shapes:
    print (s.height.cm,s.width.cm,s._inline.graphic.graphicData.pic.nvPicPr.cNvPr.name)
Run Code Online (Sandbox Code Playgroud)

产量

21.228  15.920 IMG_20160910_220903848.jpg
Run Code Online (Sandbox Code Playgroud)

事实上,我想知道是否有更简单的方法来获取图像名称,例如s.height.cm以cm为单位获取高度.我的主要要求是了解图像在文档中的位置,因为我需要提取图像并对其进行一些处理,然后再将图像放回到同一位置

python python-docx

5
推荐指数
2
解决办法
4427
查看次数

我尝试在Django2中迁移时出错

我有一个问题(至少我认为).我是这一切的新人,所以我道歉如果我问一些愚蠢的事情.我有一些网站正常工作.当我尝试进行迁移(python manage.py makemigrations)时,一切都通过了,我收到了有多少新模型的消息,等等.但是,当我在迁移后运行时,我得到了以下输出:

Operations to perform:
  Apply all migrations: admin, auth, comments, contenttypes, news, sessions
  Running migrations:
   Applying comments.0003_auto_20180816_2158...Traceback (most recent call last):
   File "../venv/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
  return self.cursor.execute(sql, params)
  psycopg2.ProgrammingError: syntax error at or near "WITH ORDINALITY"
  LINE 6:                     FROM unnest(c.conkey) WITH ORDINALITY co...
                                              ^


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
   execute_from_command_line(sys.argv)
  File ".../venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute() …
Run Code Online (Sandbox Code Playgroud)

python django

3
推荐指数
2
解决办法
5256
查看次数

Django下载文件无效

我正在尝试在用户的计算机上创建用于下载上载文件的脚本.问题是下载根本不起作用(它要么下载我一个空文件,要么给我一些错误).

最后一个错误是:强制转换为Unicode:需要字符串或缓冲区,找到FieldFile

def download_course(request, id):
    course = Courses.objects.get(pk = id).course

    path_to_file = 'root/cFolder'
    filename = course # Select your file here.                                
    wrapper = FileWrapper(file(course))
    content_type = mimetypes.guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type = content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(course)

    return response
Run Code Online (Sandbox Code Playgroud)

如何正确声明文件名,以便每次都知道要下载的文件:文件名实际上是'course',如上所述

谢谢 !

forms django file download

2
推荐指数
1
解决办法
6234
查看次数

Django - URL 和命名空间

我正在 Book 应用程序中构建 Django 模板,并使用 URL 标签重定向到 Account 应用程序的 URL。但它说account' is not a registered namespace

书.url:

app_name = 'book'
urlpatterns = [
    path('', views.HomePageView.as_view(), name='home'),
    path('account/', include('account.urls', namespace='account'))
]
Run Code Online (Sandbox Code Playgroud)

书评:

class HomePageView(generic.TemplateView):
    template_name = 'book/home.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['all_books'] = Book.objects.all()
        return context
Run Code Online (Sandbox Code Playgroud)

模板/book/home.html:

<div id="register">
    <p>
        <a href="{% url 'account:register' %}"> Sign Up </a>
    </p>
</div>
Run Code Online (Sandbox Code Playgroud)

帐户/网址:

app_name='account'
urlpatterns=(
    path('register/', views.RegisterView.as_view(), name='register'),
    path('successful/', views.successful_created, name='successful'),
)
Run Code Online (Sandbox Code Playgroud)

python django

2
推荐指数
1
解决办法
1071
查看次数

先前函数调用中保留的函数参数中的默认值

我注意到 python 中有一个奇怪的行为,有人能给我这种行为的原因吗?

如果我调用没有属性的函数,则默认值将保留其状态。您可以查看以下示例以更好地理解

class EvenStream(object):
    def __init__(self):
        self.current = 0

    def get_next(self):
        to_return = self.current
        self.current += 2
        return to_return


class OddStream(object):
    def __init__(self):
        self.current = 1

    def get_next(self):
        to_return = self.current
        self.current += 2
        return to_return


def print_from_stream(n, stream=EvenStream()):
    for _ in range(n):
        print(stream.get_next())


print_from_stream(2)
print('*****')
print_from_stream(2)
print('*****')
print_from_stream(2, OddStream())
print('*****')
print_from_stream(2, OddStream())
Run Code Online (Sandbox Code Playgroud)

输出:我期待 0,2,0,2 但它给了我 0,2,4,6

0
2
*****
4
6
*****
1
3
*****
1
3
Run Code Online (Sandbox Code Playgroud)

python python-3.x

1
推荐指数
1
解决办法
867
查看次数