Skip to content

Commit 59dc0dc

Browse files
committed
Merge branch 'tume-master'
* tume-master: Use list Use newstr from future Remove extra list call when iterating Experimental python3 support
2 parents 955c954 + 70f0c59 commit 59dc0dc

41 files changed

Lines changed: 259 additions & 138 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

Makefile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@ docker:
44
test: docker
55
sh -c "docker run --rm -i -t -p 27017:27017 -p 6379:6379 -p 5555:5555 -p 20020:20020 -v `pwd`:/app:rw -w /app mrq_local python -m pytest tests/ -v --instafail"
66

7+
test3: docker
8+
sh -c "docker run --rm -i -t -p 27017:27017 -p 6379:6379 -p 5555:5555 -p 20020:20020 -v `pwd`:/app:rw -w /app mrq_local python3 -m pytest tests/ -v --instafail"
9+
710
shell:
811
sh -c "docker run --rm -i -t -p 27017:27017 -p 6379:6379 -p 5555:5555 -p 20020:20020 -p 8000:8000 -v `pwd`:/app:rw -w /app mrq_local bash"
912

examples/simple_crawler/crawler.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -86,16 +86,16 @@ def run(self, params):
8686

8787
collection = connections.mongodb_jobs.simple_crawler_urls
8888

89-
print
90-
print "Crawl stats"
91-
print "==========="
92-
print "URLs queued: %s" % collection.find().count()
93-
print "URLs successfully crawled: %s" % collection.find({"fetched_date": {"$exists": True}}).count()
94-
print "URLs redirected: %s" % collection.find({"redirected_to": {"$exists": True}}).count()
95-
print "Bytes fetched: %s" % (list(collection.aggregate(
89+
print()
90+
print( "Crawl stats")
91+
print( "===========")
92+
print( "URLs queued: %s" % collection.find().count())
93+
print( "URLs successfully crawled: %s" % collection.find({"fetched_date": {"$exists": True}}).count())
94+
print( "URLs redirected: %s" % collection.find({"redirected_to": {"$exists": True}}).count())
95+
print( "Bytes fetched: %s" % (list(collection.aggregate(
9696
{"$group": {"_id": None, "sum": {"$sum": "$html_length"}}}
97-
)) or [{}])[0].get("sum", 0)
98-
print
97+
)) or [{}])[0].get("sum", 0))
98+
print()
9999

100100

101101
class Reset(Task):

mrq/basetasks/cleaning.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from builtins import str
12
from mrq.queue import Queue
23
from mrq.task import Task
34
from mrq.job import Job

mrq/basetasks/utils.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from __future__ import print_function
2+
from future.utils import itervalues
3+
from builtins import str
14
from mrq.task import Task
25
from mrq.queue import Queue
36
from bson import ObjectId
@@ -50,7 +53,7 @@ def build_query(self):
5053
if self.params.get("params"):
5154
params_dict = json.loads(self.params.get("params")) # pylint: disable=no-member
5255

53-
for key in params_dict.keys():
56+
for key in params_dict:
5457
query["params.%s" % key] = params_dict[key]
5558

5659
return query
@@ -76,7 +79,7 @@ def perform_action(self, action, query, destination_queue):
7679
else:
7780

7881
tasks_defs = get_current_config().get("tasks", {})
79-
tasks_ttls = [cfg.get("result_ttl", 0) for cfg in tasks_defs.values()]
82+
tasks_ttls = [cfg.get("result_ttl", 0) for cfg in itervalues(tasks_defs)]
8083

8184
result_ttl = max([default_job_timeout] + tasks_ttls)
8285

@@ -92,7 +95,7 @@ def perform_action(self, action, query, destination_queue):
9295
# In this case we could also loose some jobs that were queued after
9396
# the MongoDB update. They will be "lost" and requeued later like the other case
9497
# after the Redis BLPOP
95-
if query.keys() == ["queue"]:
98+
if list(query.keys()) == ["queue"]:
9699
Queue(query["queue"]).empty()
97100

98101
elif action in ("requeue", "requeue_retry"):
@@ -135,6 +138,6 @@ def perform_action(self, action, query, destination_queue):
135138
Queue(destination_queue or queue, add_to_known_queues=True).enqueue_job_ids(
136139
[str(x) for x in jobs_by_queue[queue]])
137140

138-
print stats
141+
print(stats)
139142

140143
return stats

mrq/bin/mrq_run.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
#!/usr/bin/env python
2+
from __future__ import print_function
3+
24
import os
35

46
# Needed to make getaddrinfo() work in pymongo on Mac OS X
@@ -40,13 +42,13 @@ def main():
4042
# mrq-run taskpath a 1 b 2 => {"a": "1", "b": "2"}
4143
for group in utils.group_iter(cfg["taskargs"], n=2):
4244
if len(group) != 2:
43-
print "Number of arguments wasn't even"
45+
print("Number of arguments wasn't even")
4446
sys.exit(1)
4547
params[group[0]] = group[1]
4648

4749
if cfg["queue"]:
4850
ret = queue_job(cfg["taskpath"], params, queue=cfg["queue"])
49-
print ret
51+
print(ret)
5052
else:
5153
worker_class = load_class_by_path(cfg["worker_class"])
5254
job = worker_class.job_class(None)
@@ -58,7 +60,7 @@ def main():
5860
job.datestarted = datetime.datetime.utcnow()
5961
set_current_job(job)
6062
ret = job.perform()
61-
print json_stdlib.dumps(ret, cls=MongoJSONEncoder) # pylint: disable=no-member
63+
print(json_stdlib.dumps(ret, cls=MongoJSONEncoder)) # pylint: disable=no-member
6264

6365
# This shouldn't be needed as the process will exit and close any remaining sockets
6466
# connections.redis.connection_pool.disconnect()

mrq/bin/mrq_worker.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#!/usr/bin/env python
22
import os
3+
from builtins import str
34

45
# Needed to make getaddrinfo() work in pymongo on Mac OS X
56
# Docs mention it's a better choice for Linux as well.
@@ -8,15 +9,19 @@
89
os.environ["GEVENT_RESOLVER"] = "ares"
910

1011
from gevent import monkey
11-
monkey.patch_all()
12+
monkey.patch_all(subprocess=False)
1213

1314
import sys
1415
import tempfile
1516
import signal
16-
import subprocess32 as subprocess
1717
import psutil
1818
import argparse
1919

20+
try:
21+
import subprocess32 as subprocess
22+
except:
23+
import subprocess
24+
2025
sys.path.insert(0, os.getcwd())
2126

2227
from mrq import config

mrq/config.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import print_function
2+
from builtins import str
13
import argparse
24
import os
35
import sys
@@ -325,7 +327,7 @@ def add_parser_args(parser, config_type):
325327
'--report_file',
326328
default="",
327329
action='store',
328-
type=unicode,
330+
type=str,
329331
help='Filepath of a json dump of the worker status. Disabled if none')
330332

331333
parser.add_argument(
@@ -422,7 +424,7 @@ def get_config(
422424
# line
423425
from_args = {}
424426
if "args" in sources:
425-
for k, v in parser.parse_args().__dict__.iteritems():
427+
for k, v in parser.parse_args().__dict__.items():
426428
if default_config[k] != v:
427429
from_args[k] = v
428430

@@ -443,7 +445,7 @@ def get_config(
443445
sys.path.insert(0, os.path.dirname(config_file))
444446
config_module = __import__(os.path.basename(config_file.replace(".py", "")))
445447
sys.path.pop(0)
446-
for k, v in config_module.__dict__.iteritems():
448+
for k, v in config_module.__dict__.items():
447449

448450
# We only keep variables starting with an uppercase character.
449451
if k[0].isupper():
@@ -452,7 +454,7 @@ def get_config(
452454
# Merge the config in the order given by the user
453455
merged_config = default_config
454456

455-
config_keys = set(default_config.keys() + from_file.keys())
457+
config_keys = set(list(default_config.keys()) + list(from_file.keys()))
456458

457459
for part in sources:
458460
for name in config_keys:
@@ -484,11 +486,11 @@ def print_profiling():
484486
atexit.register(print_profiling)
485487

486488
if merged_config["version"]:
487-
print "MRQ version: %s" % VERSION
488-
print "Python version: %s" % sys.version
489+
print("MRQ version: %s" % VERSION)
490+
print("Python version: %s" % sys.version)
489491
sys.exit(1)
490492

491493
if "no_import_patch" in from_args:
492-
print "WARNING: --no_import_patch will be deprecated in MRQ 1.0!"
494+
print("WARNING: --no_import_patch will be deprecated in MRQ 1.0!")
493495

494496
return merged_config

mrq/context.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1+
from future import standard_library
2+
standard_library.install_aliases()
3+
from builtins import next
4+
from builtins import map
5+
from past.builtins import basestring
16
from .logger import Logger
27
import gevent
38
import gevent.pool
4-
import urlparse
9+
import urllib.parse
510
import time
611
import pymongo
712
import traceback
@@ -108,12 +113,12 @@ def versiontuple(v):
108113
return tuple(map(int, (v.split("."))))
109114

110115
if attr.startswith("redis"):
111-
if type(config_obj) in [str, unicode]:
116+
if isinstance(config_obj, basestring):
112117

113118
import redis as pyredis
114119

115-
urlparse.uses_netloc.append('redis')
116-
redis_url = urlparse.urlparse(config_obj)
120+
urllib.parse.uses_netloc.append('redis')
121+
redis_url = urllib.parse.urlparse(config_obj)
117122

118123
log.info("%s: Connecting to Redis at %s..." %
119124
(attr, redis_url.hostname))
@@ -124,7 +129,8 @@ def versiontuple(v):
124129
db=int((redis_url.path or "").replace("/", "") or "0"),
125130
password=redis_url.password,
126131
max_connections=int(config.get("redis_max_connections")),
127-
timeout=int(config.get("redis_timeout"))
132+
timeout=int(config.get("redis_timeout")),
133+
decode_responses=True
128134
)
129135
return pyredis.StrictRedis(connection_pool=redis_pool)
130136

@@ -134,7 +140,7 @@ def versiontuple(v):
134140

135141
elif attr.startswith("mongodb"):
136142

137-
if type(config_obj) in [str, unicode]:
143+
if isinstance(config_obj, basestring):
138144

139145
if attr == "mongodb_logs" and config_obj == "1":
140146
return connections.mongodb_jobs
@@ -218,7 +224,7 @@ def inner_func(*args):
218224

219225
try:
220226
ret = func(*args)
221-
except Exception, exc:
227+
except Exception as exc:
222228
trace = traceback.format_exc()
223229
log.error("Error in subpool: %s \n%s" % (exc, trace))
224230
raise
@@ -271,7 +277,7 @@ def inner_func(*args):
271277

272278
try:
273279
ret = func(*args)
274-
except Exception, exc:
280+
except Exception as exc:
275281
trace = traceback.format_exc()
276282
log.error("Error in subpool: %s \n%s" % (exc, trace))
277283
raise

mrq/dashboard/app.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
from __future__ import print_function
2+
from future import standard_library
3+
standard_library.install_aliases()
4+
from future.utils import iteritems
15
from gevent import monkey
26
monkey.patch_all()
37

@@ -41,7 +45,7 @@
4145
@requires_auth
4246
def root():
4347
return render_template("index.html", MRQ_CONFIG={
44-
k: v for k, v in cfg.items() if k in WHITELISTED_MRQ_CONFIG_KEYS
48+
k: v for k, v in iteritems(cfg) if k in WHITELISTED_MRQ_CONFIG_KEYS
4549
})
4650

4751

@@ -149,10 +153,10 @@ def build_api_datatables_query(req):
149153
try:
150154
params_dict = json.loads(req.args.get("params"))
151155

152-
for key in params_dict.keys():
156+
for key in params_dict:
153157
query["params.%s" % key] = params_dict[key]
154158
except Exception as e: # pylint: disable=broad-except
155-
print "Error will converting form JSON: %s" % e
159+
print("Error will converting form JSON: %s" % e)
156160

157161
return query
158162

@@ -313,7 +317,7 @@ def api_job_traceback(job_id):
313317
@app.route('/api/jobaction', methods=["POST"])
314318
@requires_auth
315319
def api_job_action():
316-
params = {k: v for k, v in request.form.iteritems()}
320+
params = {k: v for k, v in iteritems(request.form)}
317321
if params.get("status") and "-" in params.get("status"):
318322
params["status"] = params.get("status").split("-")
319323
return jsonify({"job_id": queue_job("mrq.basetasks.utils.JobAction",

mrq/job.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
from future import standard_library
2+
standard_library.install_aliases()
3+
from builtins import str
4+
from builtins import object
15
import datetime
26
from bson import ObjectId
37
from redis.exceptions import LockError
@@ -11,12 +15,12 @@
1115
from collections import defaultdict
1216
import traceback
1317
import sys
14-
import urlparse
18+
import urllib.parse
1519
import re
1620
import linecache
1721
import fnmatch
1822
import encodings
19-
import copy_reg
23+
import copyreg
2024
from . import context
2125

2226

@@ -55,7 +59,10 @@ def __init__(self, job_id, queue=None, start=False, fetch=False):
5559
if job_id is None:
5660
self.id = None
5761
else:
58-
self.id = ObjectId(job_id)
62+
if isinstance(job_id, bytes):
63+
self.id = ObjectId(job_id.decode('utf-8'))
64+
else:
65+
self.id = ObjectId(job_id)
5966

6067
self.data = None
6168
self.saved = True
@@ -516,10 +523,10 @@ def set_current_io(self, io_data):
516523
def trace_memory_clean_caches(self):
517524
""" Avoid polluting results with some builtin python caches """
518525

519-
urlparse.clear_cache()
526+
urllib.parse.clear_cache()
520527
re.purge()
521528
linecache.clearcache()
522-
copy_reg.clear_extension_cache()
529+
copyreg.clear_extension_cache()
523530

524531
if hasattr(fnmatch, "purge"):
525532
fnmatch.purge() # pylint: disable=no-member

0 commit comments

Comments
 (0)