##// END OF EJS Templates
py3: migrate from urllib2 to urllib...
Mads Kiilerich -
r8068:22b40db4 default
parent child Browse files
Show More
@@ -29,7 +29,7 b' import os'
29 import pprint
29 import pprint
30 import random
30 import random
31 import sys
31 import sys
32 import urllib2
32 import urllib.request
33
33
34 from kallithea.lib import ext_json
34 from kallithea.lib import ext_json
35 from kallithea.lib.utils2 import ascii_bytes
35 from kallithea.lib.utils2 import ascii_bytes
@@ -68,10 +68,10 b' def api_call(apikey, apihost, method=Non'
68 raise Exception('please specify method name !')
68 raise Exception('please specify method name !')
69 apihost = apihost.rstrip('/')
69 apihost = apihost.rstrip('/')
70 id_ = random.randrange(1, 9999)
70 id_ = random.randrange(1, 9999)
71 req = urllib2.Request('%s/_admin/api' % apihost,
71 req = urllib.request.Request('%s/_admin/api' % apihost,
72 data=ascii_bytes(ext_json.dumps(_build_data(id_))),
72 data=ascii_bytes(ext_json.dumps(_build_data(id_))),
73 headers={'content-type': 'text/plain'})
73 headers={'content-type': 'text/plain'})
74 ret = urllib2.urlopen(req)
74 ret = urllib.request.urlopen(req)
75 raw_json = ret.read()
75 raw_json = ret.read()
76 json_data = ext_json.loads(raw_json)
76 json_data = ext_json.loads(raw_json)
77 id_ret = json_data['id']
77 id_ret = json_data['id']
@@ -27,7 +27,7 b' Original author and date, and relevant c'
27
27
28 from __future__ import print_function
28 from __future__ import print_function
29
29
30 import urllib2
30 import urllib.request
31 import uuid
31 import uuid
32 from configparser import ConfigParser
32 from configparser import ConfigParser
33
33
@@ -83,9 +83,9 b' class API(object):'
83
83
84 data = ascii_bytes(ext_json.dumps(data))
84 data = ascii_bytes(ext_json.dumps(data))
85 headers = {'content-type': 'text/plain'}
85 headers = {'content-type': 'text/plain'}
86 req = urllib2.Request(self.url, data, headers)
86 req = urllib.request.Request(self.url, data, headers)
87
87
88 response = urllib2.urlopen(req)
88 response = urllib.request.urlopen(req)
89 response = ext_json.load(response)
89 response = ext_json.load(response)
90
90
91 if uid != response["id"]:
91 if uid != response["id"]:
@@ -28,7 +28,8 b' Original author and date, and relevant c'
28
28
29 import base64
29 import base64
30 import logging
30 import logging
31 import urllib2
31 import urllib.parse
32 import urllib.request
32
33
33 from kallithea.lib import auth_modules, ext_json
34 from kallithea.lib import auth_modules, ext_json
34 from kallithea.lib.compat import hybrid_property
35 from kallithea.lib.compat import hybrid_property
@@ -72,10 +73,10 b' class CrowdServer(object):'
72 self._make_opener()
73 self._make_opener()
73
74
74 def _make_opener(self):
75 def _make_opener(self):
75 mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
76 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
76 mgr.add_password(None, self._uri, self.user, self.passwd)
77 mgr.add_password(None, self._uri, self.user, self.passwd)
77 handler = urllib2.HTTPBasicAuthHandler(mgr)
78 handler = urllib.request.HTTPBasicAuthHandler(mgr)
78 self.opener = urllib2.build_opener(handler)
79 self.opener = urllib.request.build_opener(handler)
79
80
80 def _request(self, url, body=None, headers=None,
81 def _request(self, url, body=None, headers=None,
81 method=None, noformat=False,
82 method=None, noformat=False,
@@ -88,7 +89,7 b' class CrowdServer(object):'
88 if headers:
89 if headers:
89 _headers.update(headers)
90 _headers.update(headers)
90 log.debug("Sent to crowd at %s:\nHeaders: %s\nBody:\n%s", url, _headers, body)
91 log.debug("Sent to crowd at %s:\nHeaders: %s\nBody:\n%s", url, _headers, body)
91 req = urllib2.Request(url, body, _headers)
92 req = urllib.request.Request(url, body, _headers)
92 if method:
93 if method:
93 req.get_method = lambda: method
94 req.get_method = lambda: method
94
95
@@ -119,14 +120,14 b' class CrowdServer(object):'
119 """Authenticate a user against crowd. Returns brief information about
120 """Authenticate a user against crowd. Returns brief information about
120 the user."""
121 the user."""
121 url = ("%s/rest/usermanagement/%s/authentication?username=%s"
122 url = ("%s/rest/usermanagement/%s/authentication?username=%s"
122 % (self._uri, self._version, urllib2.quote(username)))
123 % (self._uri, self._version, urllib.parse.quote(username)))
123 body = ascii_bytes(ext_json.dumps({"value": password}))
124 body = ascii_bytes(ext_json.dumps({"value": password}))
124 return self._request(url, body)
125 return self._request(url, body)
125
126
126 def user_groups(self, username):
127 def user_groups(self, username):
127 """Retrieve a list of groups to which this user belongs."""
128 """Retrieve a list of groups to which this user belongs."""
128 url = ("%s/rest/usermanagement/%s/user/group/nested?username=%s"
129 url = ("%s/rest/usermanagement/%s/user/group/nested?username=%s"
129 % (self._uri, self._version, urllib2.quote(username)))
130 % (self._uri, self._version, urllib.parse.quote(username)))
130 return self._request(url)
131 return self._request(url)
131
132
132
133
@@ -30,7 +30,7 b' Original author and date, and relevant c'
30
30
31 import logging
31 import logging
32 import os
32 import os
33 import urllib
33 import urllib.parse
34
34
35 import mercurial.hgweb
35 import mercurial.hgweb
36
36
@@ -121,7 +121,7 b' class SimpleHg(BaseVCSController):'
121 break
121 break
122 action = 'pull'
122 action = 'pull'
123 for cmd_arg in hgarg[5:].split(';'):
123 for cmd_arg in hgarg[5:].split(';'):
124 cmd, _args = urllib.unquote_plus(cmd_arg).split(' ', 1)
124 cmd, _args = urllib.parse.unquote_plus(cmd_arg).split(' ', 1)
125 op = cmd_mapping.get(cmd, 'push')
125 op = cmd_mapping.get(cmd, 'push')
126 if op != 'pull':
126 if op != 'pull':
127 assert op == 'push'
127 assert op == 'push'
@@ -1,7 +1,7 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 import json
2 import json
3 import urllib
3 import urllib.parse
4 import urllib2
4 import urllib.request
5
5
6
6
7 class RecaptchaResponse(object):
7 class RecaptchaResponse(object):
@@ -30,13 +30,13 b' def submit(g_recaptcha_response, private'
30 return s.encode('utf-8')
30 return s.encode('utf-8')
31 return s
31 return s
32
32
33 params = urllib.urlencode({
33 params = urllib.parse.urlencode({
34 'secret': encode_if_necessary(private_key),
34 'secret': encode_if_necessary(private_key),
35 'remoteip': encode_if_necessary(remoteip),
35 'remoteip': encode_if_necessary(remoteip),
36 'response': encode_if_necessary(g_recaptcha_response),
36 'response': encode_if_necessary(g_recaptcha_response),
37 }).encode('ascii')
37 }).encode('ascii')
38
38
39 req = urllib2.Request(
39 req = urllib.request.Request(
40 url="https://www.google.com/recaptcha/api/siteverify",
40 url="https://www.google.com/recaptcha/api/siteverify",
41 data=params,
41 data=params,
42 headers={
42 headers={
@@ -45,7 +45,7 b' def submit(g_recaptcha_response, private'
45 }
45 }
46 )
46 )
47
47
48 httpresp = urllib2.urlopen(req)
48 httpresp = urllib.request.urlopen(req)
49 return_values = json.loads(httpresp.read())
49 return_values = json.loads(httpresp.read())
50 httpresp.close()
50 httpresp.close()
51
51
@@ -36,7 +36,7 b' import os'
36 import pwd
36 import pwd
37 import re
37 import re
38 import time
38 import time
39 import urllib
39 import urllib.parse
40
40
41 import urlobject
41 import urlobject
42 from tg.i18n import ugettext as _
42 from tg.i18n import ugettext as _
@@ -322,14 +322,14 b' def credentials_filter(uri):'
322
322
323 def get_clone_url(clone_uri_tmpl, prefix_url, repo_name, repo_id, username=None):
323 def get_clone_url(clone_uri_tmpl, prefix_url, repo_name, repo_id, username=None):
324 parsed_url = urlobject.URLObject(prefix_url)
324 parsed_url = urlobject.URLObject(prefix_url)
325 prefix = safe_unicode(urllib.unquote(parsed_url.path.rstrip('/')))
325 prefix = safe_unicode(urllib.parse.unquote(parsed_url.path.rstrip('/')))
326 try:
326 try:
327 system_user = pwd.getpwuid(os.getuid()).pw_name
327 system_user = pwd.getpwuid(os.getuid()).pw_name
328 except Exception: # TODO: support all systems - especially Windows
328 except Exception: # TODO: support all systems - especially Windows
329 system_user = 'kallithea' # hardcoded default value ...
329 system_user = 'kallithea' # hardcoded default value ...
330 args = {
330 args = {
331 'scheme': parsed_url.scheme,
331 'scheme': parsed_url.scheme,
332 'user': safe_unicode(urllib.quote(safe_str(username or ''))),
332 'user': safe_unicode(urllib.parse.quote(safe_str(username or ''))),
333 'netloc': parsed_url.netloc + prefix, # like "hostname:port/prefix" (with optional ":port" and "/prefix")
333 'netloc': parsed_url.netloc + prefix, # like "hostname:port/prefix" (with optional ":port" and "/prefix")
334 'prefix': prefix, # undocumented, empty or starting with /
334 'prefix': prefix, # undocumented, empty or starting with /
335 'repo': repo_name,
335 'repo': repo_name,
@@ -14,8 +14,9 b' import logging'
14 import os
14 import os
15 import re
15 import re
16 import time
16 import time
17 import urllib
17 import urllib.error
18 import urllib2
18 import urllib.parse
19 import urllib.request
19 from collections import OrderedDict
20 from collections import OrderedDict
20
21
21 import mercurial.url # import httpbasicauthhandler, httpdigestauthhandler
22 import mercurial.url # import httpbasicauthhandler, httpdigestauthhandler
@@ -178,19 +179,19 b' class GitRepository(BaseRepository):'
178
179
179 if authinfo:
180 if authinfo:
180 # create a password manager
181 # create a password manager
181 passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
182 passmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
182 passmgr.add_password(*authinfo)
183 passmgr.add_password(*authinfo)
183
184
184 handlers.extend((mercurial.url.httpbasicauthhandler(passmgr),
185 handlers.extend((mercurial.url.httpbasicauthhandler(passmgr),
185 mercurial.url.httpdigestauthhandler(passmgr)))
186 mercurial.url.httpdigestauthhandler(passmgr)))
186
187
187 o = urllib2.build_opener(*handlers)
188 o = urllib.request.build_opener(*handlers)
188 o.addheaders = [('User-Agent', 'git/1.7.8.0')] # fake some git
189 o.addheaders = [('User-Agent', 'git/1.7.8.0')] # fake some git
189
190
190 req = urllib2.Request(
191 req = urllib.request.Request(
191 "%s?%s" % (
192 "%s?%s" % (
192 test_uri,
193 test_uri,
193 urllib.urlencode({"service": 'git-upload-pack'})
194 urllib.parse.urlencode({"service": 'git-upload-pack'})
194 ))
195 ))
195
196
196 try:
197 try:
@@ -199,12 +200,12 b' class GitRepository(BaseRepository):'
199 raise Exception('Return Code is not 200')
200 raise Exception('Return Code is not 200')
200 except Exception as e:
201 except Exception as e:
201 # means it cannot be cloned
202 # means it cannot be cloned
202 raise urllib2.URLError("[%s] org_exc: %s" % (cleaned_uri, e))
203 raise urllib.error.URLError("[%s] org_exc: %s" % (cleaned_uri, e))
203
204
204 # now detect if it's proper git repo
205 # now detect if it's proper git repo
205 gitdata = resp.read()
206 gitdata = resp.read()
206 if 'service=git-upload-pack' not in gitdata:
207 if 'service=git-upload-pack' not in gitdata:
207 raise urllib2.URLError(
208 raise urllib.error.URLError(
208 "url [%s] does not look like an git" % cleaned_uri)
209 "url [%s] does not look like an git" % cleaned_uri)
209
210
210 return True
211 return True
@@ -13,8 +13,9 b' import datetime'
13 import logging
13 import logging
14 import os
14 import os
15 import time
15 import time
16 import urllib
16 import urllib.error
17 import urllib2
17 import urllib.parse
18 import urllib.request
18 from collections import OrderedDict
19 from collections import OrderedDict
19
20
20 import mercurial.commands
21 import mercurial.commands
@@ -314,20 +315,20 b' class MercurialRepository(BaseRepository'
314
315
315 if authinfo:
316 if authinfo:
316 # create a password manager
317 # create a password manager
317 passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
318 passmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
318 passmgr.add_password(*authinfo)
319 passmgr.add_password(*authinfo)
319
320
320 handlers.extend((mercurial.url.httpbasicauthhandler(passmgr),
321 handlers.extend((mercurial.url.httpbasicauthhandler(passmgr),
321 mercurial.url.httpdigestauthhandler(passmgr)))
322 mercurial.url.httpdigestauthhandler(passmgr)))
322
323
323 o = urllib2.build_opener(*handlers)
324 o = urllib.request.build_opener(*handlers)
324 o.addheaders = [('Content-Type', 'application/mercurial-0.1'),
325 o.addheaders = [('Content-Type', 'application/mercurial-0.1'),
325 ('Accept', 'application/mercurial-0.1')]
326 ('Accept', 'application/mercurial-0.1')]
326
327
327 req = urllib2.Request(
328 req = urllib.request.Request(
328 "%s?%s" % (
329 "%s?%s" % (
329 test_uri,
330 test_uri,
330 urllib.urlencode({
331 urllib.parse.urlencode({
331 'cmd': 'between',
332 'cmd': 'between',
332 'pairs': "%s-%s" % ('0' * 40, '0' * 40),
333 'pairs': "%s-%s" % ('0' * 40, '0' * 40),
333 })
334 })
@@ -339,14 +340,14 b' class MercurialRepository(BaseRepository'
339 raise Exception('Return Code is not 200')
340 raise Exception('Return Code is not 200')
340 except Exception as e:
341 except Exception as e:
341 # means it cannot be cloned
342 # means it cannot be cloned
342 raise urllib2.URLError("[%s] org_exc: %s" % (cleaned_uri, e))
343 raise urllib.error.URLError("[%s] org_exc: %s" % (cleaned_uri, e))
343
344
344 if not url_prefix: # skip svn+http://... (and git+... too)
345 if not url_prefix: # skip svn+http://... (and git+... too)
345 # now check if it's a proper hg repo
346 # now check if it's a proper hg repo
346 try:
347 try:
347 mercurial.httppeer.instance(repoui or mercurial.ui.ui(), url, False).lookup(b'tip')
348 mercurial.httppeer.instance(repoui or mercurial.ui.ui(), url, False).lookup(b'tip')
348 except Exception as e:
349 except Exception as e:
349 raise urllib2.URLError(
350 raise urllib.error.URLError(
350 "url [%s] does not look like an hg repo org_exc: %s"
351 "url [%s] does not look like an hg repo org_exc: %s"
351 % (cleaned_uri, e))
352 % (cleaned_uri, e))
352
353
@@ -490,7 +491,7 b' class MercurialRepository(BaseRepository'
490 """
491 """
491 url = safe_str(url)
492 url = safe_str(url)
492 if url != 'default' and '://' not in url:
493 if url != 'default' and '://' not in url:
493 url = "file:" + urllib.pathname2url(url)
494 url = "file:" + urllib.request.pathname2url(url)
494 return url
495 return url
495
496
496 def get_changeset(self, revision=None):
497 def get_changeset(self, revision=None):
@@ -1,7 +1,7 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 import os
3 import os
4 import urllib
4 import urllib.parse
5
5
6 import mock
6 import mock
7 import pytest
7 import pytest
@@ -410,7 +410,7 b' class _BaseTestCase(base.TestController)'
410 assert response.json == {u'result': True}
410 assert response.json == {u'result': True}
411 self.checkSessionFlash(response,
411 self.checkSessionFlash(response,
412 u'Created repository <a href="/%s">%s</a>'
412 u'Created repository <a href="/%s">%s</a>'
413 % (urllib.quote(repo_name), repo_name_unicode))
413 % (urllib.parse.quote(repo_name), repo_name_unicode))
414 # test if the repo was created in the database
414 # test if the repo was created in the database
415 new_repo = Session().query(Repository) \
415 new_repo = Session().query(Repository) \
416 .filter(Repository.repo_name == repo_name_unicode).one()
416 .filter(Repository.repo_name == repo_name_unicode).one()
@@ -1,6 +1,6 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 import urllib
3 import urllib.parse
4
4
5 from kallithea.lib.utils2 import safe_str, safe_unicode
5 from kallithea.lib.utils2 import safe_str, safe_unicode
6 from kallithea.model.db import Repository, User
6 from kallithea.model.db import Repository, User
@@ -159,7 +159,7 b' class _BaseTestCase(base.TestController)'
159 response = self.app.get(base.url(controller='forks', action='forks',
159 response = self.app.get(base.url(controller='forks', action='forks',
160 repo_name=repo_name))
160 repo_name=repo_name))
161 response.mustcontain(
161 response.mustcontain(
162 """<a href="/%s">%s</a>""" % (urllib.quote(fork_name), fork_name)
162 """<a href="/%s">%s</a>""" % (urllib.parse.quote(fork_name), fork_name)
163 )
163 )
164 fork_repo = Repository.get_by_repo_name(safe_unicode(fork_name))
164 fork_repo = Repository.get_by_repo_name(safe_unicode(fork_name))
165 assert fork_repo
165 assert fork_repo
@@ -180,7 +180,7 b' class _BaseTestCase(base.TestController)'
180 response = self.app.get(base.url(controller='forks', action='forks',
180 response = self.app.get(base.url(controller='forks', action='forks',
181 repo_name=fork_name))
181 repo_name=fork_name))
182 response.mustcontain(
182 response.mustcontain(
183 """<a href="/%s">%s</a>""" % (urllib.quote(fork_name_2), fork_name_2)
183 """<a href="/%s">%s</a>""" % (urllib.parse.quote(fork_name_2), fork_name_2)
184 )
184 )
185
185
186 # remove these forks
186 # remove these forks
@@ -32,7 +32,7 b' import os'
32 import re
32 import re
33 import tempfile
33 import tempfile
34 import time
34 import time
35 import urllib2
35 import urllib.request
36 from subprocess import PIPE, Popen
36 from subprocess import PIPE, Popen
37 from tempfile import _RandomNameSequence
37 from tempfile import _RandomNameSequence
38
38
@@ -329,11 +329,11 b' class TestVCSOperations(base.TestControl'
329 owner=base.TEST_USER_ADMIN_LOGIN,
329 owner=base.TEST_USER_ADMIN_LOGIN,
330 repo_type=vt.repo_type),
330 repo_type=vt.repo_type),
331 }
331 }
332 req = urllib2.Request(
332 req = urllib.request.Request(
333 'http://%s:%s/_admin/api' % webserver.server_address,
333 'http://%s:%s/_admin/api' % webserver.server_address,
334 data=ascii_bytes(json.dumps(params)),
334 data=ascii_bytes(json.dumps(params)),
335 headers={'content-type': 'application/json'})
335 headers={'content-type': 'application/json'})
336 response = urllib2.urlopen(req)
336 response = urllib.request.urlopen(req)
337 result = json.loads(response.read())
337 result = json.loads(response.read())
338 # Expect something like:
338 # Expect something like:
339 # {u'result': {u'msg': u'Created new repository `new_XXX`', u'task': None, u'success': True}, u'id': 7, u'error': None}
339 # {u'result': {u'msg': u'Created new repository `new_XXX`', u'task': None, u'success': True}, u'id': 7, u'error': None}
@@ -37,8 +37,8 b' import os'
37 import sys
37 import sys
38 import tempfile
38 import tempfile
39 import time
39 import time
40 import urllib
40 import urllib.parse
41 import urllib2
41 import urllib.request
42 from os.path import dirname
42 from os.path import dirname
43
43
44 from kallithea.lib import vcs
44 from kallithea.lib import vcs
@@ -73,13 +73,13 b' PROJECTS = ['
73
73
74
74
75 cj = http.cookiejar.FileCookieJar(os.path.join(tempfile.gettempdir(), 'rc_test_cookie.txt'))
75 cj = http.cookiejar.FileCookieJar(os.path.join(tempfile.gettempdir(), 'rc_test_cookie.txt'))
76 o = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
76 o = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
77 o.addheaders = [
77 o.addheaders = [
78 ('User-agent', 'kallithea-crawler'),
78 ('User-agent', 'kallithea-crawler'),
79 ('Accept-Language', 'en - us, en;q = 0.5')
79 ('Accept-Language', 'en - us, en;q = 0.5')
80 ]
80 ]
81
81
82 urllib2.install_opener(o)
82 urllib.request.install_opener(o)
83
83
84
84
85 def _get_repo(proj):
85 def _get_repo(proj):
@@ -101,7 +101,7 b' def test_changelog_walk(proj, pages=100)'
101
101
102 page = '/'.join((proj, 'changelog',))
102 page = '/'.join((proj, 'changelog',))
103
103
104 full_uri = (BASE_URI % page) + '?' + urllib.urlencode({'page': i})
104 full_uri = (BASE_URI % page) + '?' + urllib.parse.urlencode({'page': i})
105 s = time.time()
105 s = time.time()
106 f = o.open(full_uri)
106 f = o.open(full_uri)
107
107
@@ -1,7 +1,7 b''
1 import datetime
1 import datetime
2 import os
2 import os
3 import sys
3 import sys
4 import urllib2
4 import urllib.error
5
5
6 import mock
6 import mock
7 import pytest
7 import pytest
@@ -32,7 +32,7 b' class TestGitRepository(object):'
32
32
33 def test_git_cmd_injection(self):
33 def test_git_cmd_injection(self):
34 repo_inject_path = TEST_GIT_REPO + '; echo "Cake";'
34 repo_inject_path = TEST_GIT_REPO + '; echo "Cake";'
35 with pytest.raises(urllib2.URLError):
35 with pytest.raises(urllib.error.URLError):
36 # Should fail because URL will contain the parts after ; too
36 # Should fail because URL will contain the parts after ; too
37 GitRepository(get_new_dir('injection-repo'), src_url=repo_inject_path, update_after_clone=True, create=True)
37 GitRepository(get_new_dir('injection-repo'), src_url=repo_inject_path, update_after_clone=True, create=True)
38
38
General Comments 0
You need to be logged in to leave comments. Login now