knktc's Notes

python, cloud, linux...

0%

Fix Special Characters in Celery Broker Passwords

For security reasons, passwords often include special characters such as punctuation. But when using RabbitMQ with Celery, a password containing characters like ? can break broker URL parsing.

Suppose we want to connect to a RabbitMQ server with username admin and password mypass?1234. A broker URL might look like this:

1
amqp://admin:mypass?1234@test.knktc.com//

And the Celery code might look like this:

1
2
3
4
5
6
7
8
9
from celery import Celery

RMQ_URL = 'amqp://admin:mypass?1234@test.knktc.com//'
app = Celery('tasks', broker=RMQ_URL)


@app.task
def add(x, y):
return x + y

Running that code produces an error like this:

1
ValueError: invalid literal for int() with base 10: 'mypass'

The problem is that the ? in the password is being interpreted as part of the URL syntax.

The solution is to URL-encode the password first:

1
2
3
4
5
6
7
8
9
10
11
from celery import Celery
from urllib import quote

PASSWORD = quote('mypass?1234')
RMQ_URL = 'amqp://admin:{}@test.knktc.com//'.format(PASSWORD)
app = Celery('tasks', broker=RMQ_URL)


@app.task
def add(x, y):
return x + y

After that, the connection works normally.

如果我的文字帮到了您,那么可不可以请我喝罐可乐?