首页 \ 问答 \ Django无法连接到docker中的redis(Django cant connect to redis in docker)

Django无法连接到docker中的redis(Django cant connect to redis in docker)

对不起我的英语不好。 我在django有项目,在我的项目中我想用celery作为后台任务,现在我需要在docker中为这个库设置设置。 这是我的docker文件:

FROM python:3

MAINTAINER Alex2

RUN apt-get update

# Install wkhtmltopdf
RUN curl -L#o wk.tar.xz https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz \
    && tar xf wk.tar.xz \
    && cp wkhtmltox/bin/wkhtmltopdf /usr/bin \
    && cp wkhtmltox/bin/wkhtmltoimage /usr/bin \
    && rm wk.tar.xz \
    && rm -r wkhtmltox

RUN apt-get install -y cron

# for celery
ENV APP_USER user
ENV APP_ROOT /src

RUN groupadd -r ${APP_USER} \
    && useradd -r -m \
    --home-dir ${APP_ROOT} \
    -s /usr/sbin/nologin \
    -g ${APP_USER} ${APP_USER}


# create directory for application source code
RUN mkdir -p /usr/django/app

COPY requirements.txt /usr/django/app/

WORKDIR /usr/django/app

RUN pip install -r requirements.txt

这是我的docker-compose.dev

version: '2.0'
services:
  web:
    build: .
    container_name: api_dev
    image: img/api_dev
    volumes:
      - .:/usr/django/app/
      - ./static:/static
    expose:
      - "8001"
    env_file: env/dev.env
    command: bash django_run.sh

  nginx:
    build: nginx
    container_name: ng_dev
    image: img/ng_dev
    ports:
      - "8001:8001"
    volumes:
      - ./nginx/dev_api.conf:/etc/nginx/conf.d/api.conf
      - .:/usr/django/app/
      - ./static:/static
    depends_on:
      - web
    links:
      - web:web

  db:
    image: postgres:latest
    container_name: pq01
    ports:
     - "5432:5432"

  redis:
    image: redis:latest
    container_name: rd01
    command: redis-server
    ports:
     - "8004:8004"

  celery:
    build: .
    container_name: cl01
    command: celery worker --app=myapp.celery
    volumes:
      - .:/usr/django/app/
    links:
      - db
      - redis

我有这个错误:

cl01      | User information: uid=0 euid=0 gid=0 egid=0
cl01      | 
cl01      |   uid=uid, euid=euid, gid=gid, egid=egid,
cl01      | [2018-07-31 16:40:00,207: ERROR/MainProcess] consumer: Cannot connect to redis://redis:8004/0: Error 111 connecting to redis:8004. Connection refused..
cl01      | Trying again in 2.00 seconds...
cl01      | 
cl01      | [2018-07-31 16:40:02,211: ERROR/MainProcess] consumer: Cannot connect to redis://redis:8004/0: Error 111 connecting to redis:8004. Connection refused..
cl01      | Trying again in 4.00 seconds...
cl01      | 
cl01      | [2018-07-31 16:40:06,217: ERROR/MainProcess] consumer: Cannot connect to redis://redis:8004/0: Error 111 connecting to redis:8004. Connection refused..
cl01      | Trying again in 6.00 seconds...

我不明白为什么它没有连接。 我的设置文件项目

CELERY_BROKER_URL = 'redis://redis:8004/0'
CELERY_RESULT_BACKEND = 'redis://redis:8004/0'

一切看起来都不错,但在某些文件中我可能不添加一些设置。 请帮我解决这个问题


Sorry for my english. I have project in django, In my project i want use celery for background task and now i need set settings in docker for this library. This my docker file:

FROM python:3

MAINTAINER Alex2

RUN apt-get update

# Install wkhtmltopdf
RUN curl -L#o wk.tar.xz https://downloads.wkhtmltopdf.org/0.12/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz \
    && tar xf wk.tar.xz \
    && cp wkhtmltox/bin/wkhtmltopdf /usr/bin \
    && cp wkhtmltox/bin/wkhtmltoimage /usr/bin \
    && rm wk.tar.xz \
    && rm -r wkhtmltox

RUN apt-get install -y cron

# for celery
ENV APP_USER user
ENV APP_ROOT /src

RUN groupadd -r ${APP_USER} \
    && useradd -r -m \
    --home-dir ${APP_ROOT} \
    -s /usr/sbin/nologin \
    -g ${APP_USER} ${APP_USER}


# create directory for application source code
RUN mkdir -p /usr/django/app

COPY requirements.txt /usr/django/app/

WORKDIR /usr/django/app

RUN pip install -r requirements.txt

this my docker-compose.dev

version: '2.0'
services:
  web:
    build: .
    container_name: api_dev
    image: img/api_dev
    volumes:
      - .:/usr/django/app/
      - ./static:/static
    expose:
      - "8001"
    env_file: env/dev.env
    command: bash django_run.sh

  nginx:
    build: nginx
    container_name: ng_dev
    image: img/ng_dev
    ports:
      - "8001:8001"
    volumes:
      - ./nginx/dev_api.conf:/etc/nginx/conf.d/api.conf
      - .:/usr/django/app/
      - ./static:/static
    depends_on:
      - web
    links:
      - web:web

  db:
    image: postgres:latest
    container_name: pq01
    ports:
     - "5432:5432"

  redis:
    image: redis:latest
    container_name: rd01
    command: redis-server
    ports:
     - "8004:8004"

  celery:
    build: .
    container_name: cl01
    command: celery worker --app=myapp.celery
    volumes:
      - .:/usr/django/app/
    links:
      - db
      - redis

and i have this error:

cl01      | User information: uid=0 euid=0 gid=0 egid=0
cl01      | 
cl01      |   uid=uid, euid=euid, gid=gid, egid=egid,
cl01      | [2018-07-31 16:40:00,207: ERROR/MainProcess] consumer: Cannot connect to redis://redis:8004/0: Error 111 connecting to redis:8004. Connection refused..
cl01      | Trying again in 2.00 seconds...
cl01      | 
cl01      | [2018-07-31 16:40:02,211: ERROR/MainProcess] consumer: Cannot connect to redis://redis:8004/0: Error 111 connecting to redis:8004. Connection refused..
cl01      | Trying again in 4.00 seconds...
cl01      | 
cl01      | [2018-07-31 16:40:06,217: ERROR/MainProcess] consumer: Cannot connect to redis://redis:8004/0: Error 111 connecting to redis:8004. Connection refused..
cl01      | Trying again in 6.00 seconds...

i cant understand why it not connect. My settings file project

CELERY_BROKER_URL = 'redis://redis:8004/0'
CELERY_RESULT_BACKEND = 'redis://redis:8004/0'

Everything looks like good, but mayby in some file i dont add some settings. Please help me solve this problem


原文:https://stackoverflow.com/questions/51618352
更新时间:2022-07-16 15:07

最满意答案

只需添加几层额外的嵌套函数,就可以很容易地将当前函数转换为装饰工厂:

import functools

def batchify(batch_size=200):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(d):
            assert isinstance(d, list), "data has to be in list form."
            N = len(d)
            results = []
            for i in xrange(N / batch_size + 1):
                low = i * batch_size
                high = min((i + 1) * batch_size, N)
                result = f(d[low:high])
                results.append(result)
            return [r for result in results for r in result]
        return wrapper
    return decorator

我还建议您稍微简化批处理逻辑。 在列表末尾切片不会导致任何问题。 Python将处理一个超越结束的切片,就好像它正好结束,这正是我们想要的。 我用的是:

for i in xrange(0, N, batch_size):
    result = f(d[i, i + batch_size]) # This slice still works if i+batch_size > N
    ...

It's quite easy to turn your current function into a decorator factory, just by adding a couple extra layers of nested functions:

import functools

def batchify(batch_size=200):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(d):
            assert isinstance(d, list), "data has to be in list form."
            N = len(d)
            results = []
            for i in xrange(N / batch_size + 1):
                low = i * batch_size
                high = min((i + 1) * batch_size, N)
                result = f(d[low:high])
                results.append(result)
            return [r for result in results for r in result]
        return wrapper
    return decorator

I'd also suggest that you could simplify the batching logic a bit. Slicing a past the end of the list doesn't cause any problems. Python will treat a slice that goes past the end as if it went exactly to the end, which is exactly what we want. I'd use:

for i in xrange(0, N, batch_size):
    result = f(d[i, i + batch_size]) # This slice still works if i+batch_size > N
    ...

相关问答

更多
  • 只需添加几层额外的嵌套函数,就可以很容易地将当前函数转换为装饰工厂: import functools def batchify(batch_size=200): def decorator(f): @functools.wraps(f) def wrapper(d): assert isinstance(d, list), "data has to be in list form." N = len(d) ...
  • 答案是否定的, @语法不能与任意行一起使用,需要使用mystery_func = decorator(mystery_func) 。 像这样使用@语法是一个SyntaxError 。 The answer is no, the @ syntax cannot be used with arbitrary lines, you need to use mystery_func = decorator(mystery_func). Using the @ syntax like this is a Syntax ...
  • 书籍和专业人士使用的推荐方法是混合和双重继承 。 文件: 使用Mixin和CBV 当使用DOUBLE INHERITANCE时 ,在Mixin上写的所有东西都会重叠/覆盖并与第一次导入合并。 class A: function gives a no var defined exception 1 class Bmixin: function gives b var is b class X(A, Bmixin): function give ...
  • 你在做什么叫做猴子补丁。 虽然这不是一个非常糟糕的做法,但它往往导致难以查明错误,因此请谨慎使用。 如果装饰器由于某种原因是强制性的,我建议在装饰器中向请求对象添加一些标志,并在跟踪功能中添加对该标志的检查。 装饰者: def disable_tracking(func): def wrapper(*args, **kwargs): kwargs["request"].pascalservice_do_not_track = true return func(*args, **kwarg ...
  • 仔细看看这个巨大的答案/小说 。 这是我遇到的最好的解释之一。 我可以给出的最简单的解释是装饰器将你的函数包装在另一个返回函数的函数中。 这个代码,例如: @decorate def foo(a): print a 如果您删除装饰器语法,将与此代码等效: def bar(a): print a foo = decorate(bar) 修饰器有时会传递参数,传递给动态生成的函数来改变它们的输出。 你应该阅读的另一个术语是闭包 ,因为这是允许装饰者工作的概念。 Take a good look a ...
  • 我看到你粘贴的代码 - 在pastebin上。 问题是你正在包装类的__iter__方法。 它只对每个启动的循环调用一次。 并且它会使用迭代器对象返回imediatelly - 对于__iter__返回的对象上的“next”方法的调用是什么(这是在每个for循环interacton中调用的)。 这意味着在不更改任何内容的情况下,不是在调用__iter__时使用您的探查器作为装饰器,而是以__iter__中的yield语句的其他方式使用该代码 除此之外,您最好使用timeit.timeit或其他已存在的配置文 ...
  • def override(*override_args, **override_kwargs): def outer(f): def inner(*args, **kwargs): min_args_length = min(len(args), len(override_args)) args = list(args) for i in xrange(min_args_length): ...
  • 右腿的答案很好,但我想指出在模块中定义“有意义”名称的其他方法,而不是在事实之后删除东西。 第一个选项是在模块中定义__all__ 。 __all__是作为模块接口一部分的字符串序列; 如果你的模块的用户使用了from modulename import * ,并且__all__被定义了,他们只在__all__提取名字。 所以在你的情况下,你只需添加: __all__ = ['sha256_perf', 'sha256_summary'] 靠近模块的顶部(位置无关紧要,但按照惯例,它位于靠近顶部的位置,通 ...
  • 您是否考虑过使用像JSON这样的序列化数据格式? 它很轻巧,可以轻松转换为Python词典,所有酷孩子都在使用它。 您可以以有意义的方式构造数据,但不需要包含实际代码。 然后,您可以读取该构造,获取所需的部分,然后将其传递给函数或类。 编辑 :在可能的JSON规范的简洁示例中添加了一个传递。 你的JSON: { "macros": [ { "function": "foo_func", "args": { ...
  • 装饰器语法很强大: @decorator def foo(...): ... 相当于 def foo(...): ... foo = decorator(foo) 这意味着装饰者基本上可以做任何事情 - 他们不必与装饰函数有任何关系! 例子包括: 记忆递归函数( functools.lru_cache ) 记录对函数的所有调用 实现描述符功能( property ) 将方法标记为静态( staticmethod ) The decorator syntax is powerful: @d ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。