本文整理汇总了Python中werkzeug.urls.url_quote函数的典型用法代码示例。如果您正苦于以下问题:Python url_quote函数的具体用法?Python url_quote怎么用?Python url_quote使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了url_quote函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: to_url
def to_url(self, value):
if isinstance(value, str) and value in Brother.__members__:
return url_quote(value)
elif isinstance(value, enum.Enum) and value in Brother:
return url_quote(value.name)
else:
return url_quote('oso')
开发者ID:item4,项目名称:matsu.moe,代码行数:7,代码来源:app.py
示例2: test_quoting
def test_quoting(self):
assert urls.url_quote(u'\xf6\xe4\xfc') == '%C3%B6%C3%A4%C3%BC'
assert urls.url_unquote(urls.url_quote(u'#%="\xf6')) == u'#%="\xf6'
assert urls.url_quote_plus('foo bar') == 'foo+bar'
assert urls.url_unquote_plus('foo+bar') == 'foo bar'
assert urls.url_encode({'a': None, 'b': 'foo bar'}) == 'b=foo+bar'
assert urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') == \
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
开发者ID:sean-,项目名称:werkzeug,代码行数:8,代码来源:urls.py
示例3: test_quoting
def test_quoting(self):
self.assert_strict_equal(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC')
self.assert_strict_equal(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6')
self.assert_strict_equal(urls.url_quote_plus('foo bar'), 'foo+bar')
self.assert_strict_equal(urls.url_unquote_plus('foo+bar'), u'foo bar')
self.assert_strict_equal(urls.url_encode({b'a': None, b'b': b'foo bar'}), 'b=foo+bar')
self.assert_strict_equal(urls.url_encode({u'a': None, u'b': u'foo bar'}), 'b=foo+bar')
self.assert_strict_equal(urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'),
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)')
开发者ID:TheWaWaR,项目名称:werkzeug,代码行数:9,代码来源:urls.py
示例4: match
def match(self, path_info = None, method = None, return_rule = False):
self.map.update()
if path_info is None:
path_info = self.path_info
if not isinstance(path_info, unicode):
path_info = path_info.decode(self.map.charset, 'ignore')
method = (method or self.default_method).upper()
path = u'%s|/%s' % (self.subdomain, path_info.lstrip('/'))
have_match_for = set()
for rule in self.map._rules:
try:
rv = rule.match(path)
except RequestSlash:
raise RequestRedirect(str('%s://%s%s%s/%s/' % (self.url_scheme,
self.subdomain and self.subdomain + '.' or '',
self.server_name,
self.script_name[:-1],
url_quote(path_info.lstrip('/'), self.map.charset))))
if rv is None:
continue
if rule.methods is not None and method not in rule.methods:
have_match_for.update(rule.methods)
continue
if self.map.redirect_defaults:
for r in self.map._rules_by_endpoint[rule.endpoint]:
if r.provides_defaults_for(rule) and r.suitable_for(rv, method):
rv.update(r.defaults)
subdomain, path = r.build(rv)
raise RequestRedirect(str('%s://%s%s%s/%s' % (self.url_scheme,
subdomain and subdomain + '.' or '',
self.server_name,
self.script_name[:-1],
url_quote(path.lstrip('/'), self.map.charset))))
if rule.redirect_to is not None:
if isinstance(rule.redirect_to, basestring):
def _handle_match(match):
value = rv[match.group(1)]
return rule._converters[match.group(1)].to_url(value)
redirect_url = _simple_rule_re.sub(_handle_match, rule.redirect_to)
else:
redirect_url = rule.redirect_to(self, **rv)
raise RequestRedirect(str(urljoin('%s://%s%s%s' % (self.url_scheme,
self.subdomain and self.subdomain + '.' or '',
self.server_name,
self.script_name), redirect_url)))
if return_rule:
return (rule, rv)
return (rule.endpoint, rv)
if have_match_for:
raise MethodNotAllowed(valid_methods=list(have_match_for))
raise NotFound()
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:56,代码来源:routing.py
示例5: test_quoting
def test_quoting(self):
assert urls.url_quote(u"\xf6\xe4\xfc") == "%C3%B6%C3%A4%C3%BC"
assert urls.url_unquote(urls.url_quote(u'#%="\xf6')) == u'#%="\xf6'
assert urls.url_quote_plus("foo bar") == "foo+bar"
assert urls.url_unquote_plus("foo+bar") == "foo bar"
assert urls.url_encode({"a": None, "b": "foo bar"}) == "b=foo+bar"
assert (
urls.url_fix(u"http://de.wikipedia.org/wiki/Elf (Begriffsklärung)")
== "http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29"
)
开发者ID:FakeSherlock,项目名称:Report,代码行数:10,代码来源:urls.py
示例6: get_current_url
def get_current_url(environ, root_only=False, strip_querystring=False,
host_only=False, trusted_hosts=None):
"""A handy helper function that recreates the full URL for the current
request or parts of it. Here an example:
>>> from werkzeug.test import create_environ
>>> env = create_environ("/?param=foo", "http://localhost/script")
>>> get_current_url(env)
'http://localhost/script/?param=foo'
>>> get_current_url(env, root_only=True)
'http://localhost/script/'
>>> get_current_url(env, host_only=True)
'http://localhost/'
>>> get_current_url(env, strip_querystring=True)
'http://localhost/script/'
This optionally it verifies that the host is in a list of trusted hosts.
If the host is not in there it will raise a
:exc:`~werkzeug.exceptions.SecurityError`.
:param environ: the WSGI environment to get the current URL from.
:param root_only: set `True` if you only want the root URL.
:param strip_querystring: set to `True` if you don't want the querystring.
:param host_only: set to `True` if the host URL should be returned.
:param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
for more information.
"""
from werkzeug.urls import uri_to_iri
tmp = [environ['wsgi.url_scheme'], '://', get_host(environ, trusted_hosts)]
cat = tmp.append
if host_only:
return uri_to_iri(''.join(tmp) + '/')
cat(urls.url_quote(environ.get('SCRIPT_NAME', '').rstrip('/')))
if root_only:
cat('/')
else:
cat(urls.url_quote('/' + environ.get('PATH_INFO', '').lstrip('/')))
if not strip_querystring:
qs = environ.get('QUERY_STRING')
if qs:
# QUERY_STRING really should be ascii safe but some browsers
# will send us some unicode stuff (I am looking at you IE).
# In that case we want to urllib quote it badly.
try:
if hasattr(qs, 'decode'):
qs.decode('ascii')
else:
qs.encode('ascii')
except UnicodeError:
qs = ''.join(x > 127 and '%%%02X' % x or c
for x, c in ((ord(x), x) for x in qs))
cat('?' + qs)
return uri_to_iri(''.join(tmp))
开发者ID:methane,项目名称:werkzeug,代码行数:53,代码来源:wsgi.py
示例7: test_quoting
def test_quoting():
strict_eq(urls.url_quote(u'\xf6\xe4\xfc'), '%C3%B6%C3%A4%C3%BC')
strict_eq(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6')
strict_eq(urls.url_quote_plus('foo bar'), 'foo+bar')
strict_eq(urls.url_unquote_plus('foo+bar'), u'foo bar')
strict_eq(urls.url_quote_plus('foo+bar'), 'foo%2Bbar')
strict_eq(urls.url_unquote_plus('foo%2Bbar'), u'foo+bar')
strict_eq(urls.url_encode({b'a': None, b'b': b'foo bar'}), 'b=foo+bar')
strict_eq(urls.url_encode({u'a': None, u'b': u'foo bar'}), 'b=foo+bar')
strict_eq(urls.url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)'),
'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)')
strict_eq(urls.url_quote_plus(42), '42')
strict_eq(urls.url_quote(b'\xff'), '%FF')
开发者ID:char101,项目名称:werkzeug,代码行数:13,代码来源:test_urls.py
示例8: get_current_url
def get_current_url(environ, root_only=False, strip_querystring=False,
host_only=False, trusted_hosts=None):
"""A handy helper function that recreates the full URL as IRI for the
current request or parts of it. Here an example:
>>> from werkzeug.test import create_environ
>>> env = create_environ("/?param=foo", "http://localhost/script")
>>> get_current_url(env)
'http://localhost/script/?param=foo'
>>> get_current_url(env, root_only=True)
'http://localhost/script/'
>>> get_current_url(env, host_only=True)
'http://localhost/'
>>> get_current_url(env, strip_querystring=True)
'http://localhost/script/'
This optionally it verifies that the host is in a list of trusted hosts.
If the host is not in there it will raise a
:exc:`~werkzeug.exceptions.SecurityError`.
Note that the string returned might contain unicode characters as the
representation is an IRI not an URI. If you need an ASCII only
representation you can use the :func:`~werkzeug.urls.iri_to_uri`
function:
>>> from werkzeug.urls import iri_to_uri
>>> iri_to_uri(get_current_url(env))
'http://localhost/script/?param=foo'
:param environ: the WSGI environment to get the current URL from.
:param root_only: set `True` if you only want the root URL.
:param strip_querystring: set to `True` if you don't want the querystring.
:param host_only: set to `True` if the host URL should be returned.
:param trusted_hosts: a list of trusted hosts, see :func:`host_is_trusted`
for more information.
"""
tmp = [environ['wsgi.url_scheme'], '://', get_host(environ, trusted_hosts)]
cat = tmp.append
if host_only:
return uri_to_iri(''.join(tmp) + '/')
cat(url_quote(wsgi_get_bytes(environ.get('SCRIPT_NAME', ''))).rstrip('/'))
cat('/')
if not root_only:
cat(url_quote(wsgi_get_bytes(environ.get('PATH_INFO', '')).lstrip(b'/')))
if not strip_querystring:
qs = get_query_string(environ)
if qs:
cat('?' + qs)
return uri_to_iri(''.join(tmp))
开发者ID:0x00xw,项目名称:wooyun,代码行数:49,代码来源:wsgi.py
示例9: test_quoting
def test_quoting():
strict_eq(urls.url_quote(u"\xf6\xe4\xfc"), "%C3%B6%C3%A4%C3%BC")
strict_eq(urls.url_unquote(urls.url_quote(u'#%="\xf6')), u'#%="\xf6')
strict_eq(urls.url_quote_plus("foo bar"), "foo+bar")
strict_eq(urls.url_unquote_plus("foo+bar"), u"foo bar")
strict_eq(urls.url_quote_plus("foo+bar"), "foo%2Bbar")
strict_eq(urls.url_unquote_plus("foo%2Bbar"), u"foo+bar")
strict_eq(urls.url_encode({b"a": None, b"b": b"foo bar"}), "b=foo+bar")
strict_eq(urls.url_encode({u"a": None, u"b": u"foo bar"}), "b=foo+bar")
strict_eq(
urls.url_fix(u"http://de.wikipedia.org/wiki/Elf (Begriffsklärung)"),
"http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)",
)
strict_eq(urls.url_quote_plus(42), "42")
strict_eq(urls.url_quote(b"\xff"), "%FF")
开发者ID:pallets,项目名称:werkzeug,代码行数:15,代码来源:test_urls.py
示例10: url_for
def url_for(endpoint, anchor=None, method=None, external=False, **values):
"""Generates a URL to the given endpoint with the method provided.
endpoint
: The endpoint of the URL (name of the function).
anchor
: If provided this is added as anchor to the URL.
method
: If provided this explicitly specifies an HTTP method.
external
: Set to `True`, to generate an absolute URL.
values
: The variable arguments of the URL rule
"""
try:
urls = local.urls
except AttributeError:
raise RuntimeError("You must call this function only from"
" inside a view or a template")
try:
url = urls.build(endpoint, values, method=method,
force_external=external)
except BuildError:
url = ''
if anchor is not None:
url += '#' + url_quote(anchor)
return url
开发者ID:lucuma,项目名称:Shake,代码行数:29,代码来源:helpers.py
示例11: url_for
def url_for(endpoint, **args):
"""Get the URL to an endpoint. The keyword arguments provided are used
as URL values. Unknown URL values are used as keyword argument.
Additionally there are some special keyword arguments:
`_anchor`
This string is used as URL anchor.
`_external`
If set to `True` the URL will be generated with the full server name
and `http://` prefix.
"""
if hasattr(endpoint, 'get_url_values'):
rv = endpoint.get_url_values()
if rv is not None:
if isinstance(rv, basestring):
return make_external_url(rv)
endpoint, updated_args = rv
args.update(updated_args)
anchor = args.pop('_anchor', None)
external = args.pop('_external', False)
rv = get_application().url_adapter.build(endpoint, args,
force_external=external)
if anchor is not None:
rv += '#' + url_quote(anchor)
return rv
开发者ID:UfSoft,项目名称:ILog-OLD,代码行数:26,代码来源:application.py
示例12: url_for
def url_for(self, endpoint, use_partyline=True, **values):
"""Build a URL, asking other applications if BuildError occurs locally.
This implementation is a fork of :func:`~flask.helpers.url_for`, where
the implementation you see here works around Flask's context-locals to
provide URL routing specific to ``self``. Then it implements the
wsgi_party url_for requests across Flask applications loaded into the
partyline.
"""
# Some values are popped; keep an original copy for re-requesting URL.
copy_values = copy.deepcopy(values)
blueprint_name = request.blueprint
if endpoint[:1] == '.':
if blueprint_name is not None:
endpoint = blueprint_name + endpoint
else:
endpoint = endpoint[1:]
external = values.pop('_external', False)
anchor = values.pop('_anchor', None)
method = values.pop('_method', None)
self.inject_url_defaults(endpoint, values)
url_adapter = self.create_url_adapter(request)
try:
rv = url_adapter.build(endpoint, values, method=method,
force_external=external)
except BuildError:
# We do not have this URL, ask the partyline.
if not use_partyline:
raise
for url in self.partyline.ask_around('url', (endpoint, copy_values)):
# First response wins.
return url
if anchor is not None:
rv += '#' + url_quote(anchor)
return rv
开发者ID:dplepage,项目名称:wsgi_party,代码行数:35,代码来源:flask_party.py
示例13: test_home
def test_home(self):
response = self.client.get('/user/')
self.assertRedirects(response, location='/login?next=%s' %
url_quote('/user/', safe=''))
self.login('demo', '123456')
self._test_get_request('/user/', 'user/index.html')
开发者ID:antback,项目名称:fbone,代码行数:7,代码来源:test_views.py
示例14: twitter_request
def twitter_request(self, original_url):
conf_ = conf['twitter']
original_url = oauth_base + conf_['callback_base'] + url_quote(original_url)
consumer = oauth2.Consumer(conf_['consumer_key'], conf_['consumer_secret'])
client = oauth2.Client(consumer)
q, content = client.request(conf_['token_url'], "POST",
body = url_encode({'oauth_callback':original_url}))
if q['status'] != "200":
stderr.write("Login error twitter auth:\n %s\n" % q.content)
return self.redirect('/?msg=2')
del q
oauth_data = url_decode(content)
oauth_token = oauth_data['oauth_token']
oauth_token_secret = oauth_data['oauth_token_secret']
del content
del oauth_data
f = open(oauth_secrets_path_prefix + oauth_token, 'w')
f.write(oauth_token_secret)
f.close()
self.redirect(conf_['authenticate'] + "?oauth_token=" + oauth_token)
开发者ID:mitemitreski,项目名称:myflicks,代码行数:27,代码来源:login.py
示例15: test_settings_avatar
def test_settings_avatar(self):
response = self.client.get('/user/settings/avatar')
self.assertRedirects(response, location='/login?next=%s' %
url_quote('/user/settings/avatar', safe=''))
self._login()
self._test_get_request('/user/settings/avatar', 'settings/avatar.html')
开发者ID:nickwong,项目名称:fbone,代码行数:7,代码来源:test_views.py
示例16: test_profile
def test_profile(self):
endpoint = '/settings/profile'
response = self.client.get(endpoint)
self.assertRedirects(response, location='/login?next=%s' % url_quote(endpoint, safe=''))
user = self._login()
response = self.client.get('/settings/profile')
self.assert200(response)
self.assertTemplateUsed("settings/profile.html")
data = {
'name': 'demo1',
'email': '[email protected]',
'role_id': ADMIN,
'status_id': NEW,
'real_name': user.user_detail.real_name,
'age': user.user_detail.age,
'url': user.user_detail.url,
'location': user.user_detail.location,
'bio': user.user_detail.bio,
}
response = self.client.post(endpoint, data=data)
print response.data
assert "help-block error" not in response.data
self.assert200(response)
self.assertTemplateUsed("settings/profile.html")
new_user = User.query.filter_by(name=data.get('name')).first()
assert new_user is not None
assert new_user.email == data.get('email')
assert new_user.getRole() == USER_ROLE.get(ADMIN)
assert new_user.getStatus() == USER_STATUS.get(NEW)
开发者ID:danhyun,项目名称:fbone,代码行数:33,代码来源:test_views.py
示例17: fb_request
def fb_request(self, original_url):
conf_ = conf['fb']
original_url = oauth_base + conf_['callback_base'] + url_quote(original_url)
uri = conf_['token_url'] + '?' + url_encode({'client_id': conf_['consumer_key'],
'redirect_uri': original_url})
self.redirect(uri)
开发者ID:mitemitreski,项目名称:myflicks,代码行数:7,代码来源:login.py
示例18: _get_pts_link
def _get_pts_link(self):
"""
returns an URL for the package in the Debian Package Tracking System
"""
pts_link = PTS_PREFIX + self.package
pts_link = url_quote(pts_link) # for '+' symbol in package names
return pts_link
开发者ID:chr7stos,项目名称:debsources,代码行数:7,代码来源:infobox.py
示例19: member_is_pending
def member_is_pending(username):
rv = github_api_request('GET', 'teams/%s/memberships/%s' % (
app.config['MEMBER_TEAM_ID'],
url_quote(username),
))
if rv.status_code == 404:
return False
return rv.json().get('state') == 'pending'
开发者ID:jimmydjwu83,项目名称:metaflask-api,代码行数:8,代码来源:metaflaskapi.py
示例20: run_dev_server
def run_dev_server(application):
app_pkg = tmpdir.mkdir("testsuite_app")
appfile = app_pkg.join("__init__.py")
port = next(port_generator)
appfile.write(
"\n\n".join(
(
"kwargs = {{'hostname': 'localhost', 'port': {port:d}}}".format(
port=port
),
textwrap.dedent(application),
)
)
)
monkeypatch.delitem(sys.modules, "testsuite_app", raising=False)
monkeypatch.syspath_prepend(str(tmpdir))
import testsuite_app
hostname = testsuite_app.kwargs["hostname"]
port = testsuite_app.kwargs["port"]
addr = "{}:{}".format(hostname, port)
if hostname.startswith("unix://"):
addr = hostname.split("unix://", 1)[1]
requests_url = "http+unix://" + url_quote(addr, safe="")
elif testsuite_app.kwargs.get("ssl_context", None):
requests_url = "https://localhost:{0}".format(port)
else:
requests_url = "http://localhost:{0}".format(port)
info = _ServerInfo(xprocess, addr, requests_url, port)
from xprocess import ProcessStarter
class Starter(ProcessStarter):
args = [sys.executable, __file__, str(tmpdir)]
@property
def pattern(self):
return "pid=%s" % info.request_pid()
xprocess.ensure("dev_server", Starter, restart=True)
@request.addfinalizer
def teardown():
# Killing the process group that runs the server, not just the
# parent process attached. xprocess is confused about Werkzeug's
# reloader and won't help here.
pid = info.request_pid()
if not pid:
return
if platform.system() == "Windows":
subprocess.call(["taskkill", "/F", "/T", "/PID", str(pid)])
else:
os.killpg(os.getpgid(pid), signal.SIGTERM)
return info
开发者ID:pallets,项目名称:werkzeug,代码行数:58,代码来源:conftest.py
注:本文中的werkzeug.urls.url_quote函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论