本文整理匯總了Python中urllib.parse.quote方法的典型用法代碼示例。如果您正苦於以下問題:Python parse.quote方法的具體用法?Python parse.quote怎麽用?Python parse.quote使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類urllib.parse
的用法示例。
在下文中一共展示了parse.quote方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: authorize_url
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def authorize_url(self):
"""獲取授權跳轉地址
:return: URL 地址
"""
redirect_uri = quote(self.redirect_uri, safe=b"")
url_list = [
self.OAUTH_BASE_URL,
"oauth2/authorize?appid=",
self.app_id,
"&redirect_uri=",
redirect_uri,
"&response_type=code&scope=",
self.scope,
]
if self.state:
url_list.extend(["&state=", self.state])
url_list.append("#wechat_redirect")
return "".join(url_list)
示例2: qrconnect_url
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def qrconnect_url(self):
"""生成掃碼登錄地址
:return: URL 地址
"""
redirect_uri = quote(self.redirect_uri, safe=b"")
url_list = [
self.OAUTH_BASE_URL,
"qrconnect?appid=",
self.app_id,
"&redirect_uri=",
redirect_uri,
"&response_type=code&scope=",
"snsapi_login", # scope
]
if self.state:
url_list.extend(["&state=", self.state])
url_list.append("#wechat_redirect")
return "".join(url_list)
示例3: get_url
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def get_url(cls, ticket):
"""
通過ticket換取二維碼地址
詳情請參考
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1443433542
:param ticket: 二維碼 ticket 。可以通過 :func:`create` 獲取到
:return: 返回的二維碼地址
使用示例::
from wechatpy import WeChatClient
client = WeChatClient('appid', 'secret')
url = client.qrcode.get_url('ticket data')
"""
if isinstance(ticket, dict):
ticket = ticket["ticket"]
ticket = quote(ticket)
return f"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={ticket}"
示例4: authorize_url
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def authorize_url(self, redirect_uri, state=None):
"""
構造網頁授權鏈接
詳情請參考
https://work.weixin.qq.com/api/doc#90000/90135/91022
:param redirect_uri: 授權後重定向的回調鏈接地址
:param state: 重定向後會帶上 state 參數
:return: 返回的 JSON 數據包
"""
redirect_uri = quote(redirect_uri, safe=b"")
url_list = [
self.OAUTH_BASE_URL,
"?appid=",
self._client.corp_id,
"&redirect_uri=",
redirect_uri,
"&response_type=code&scope=snsapi_base",
]
if state:
url_list.extend(["&state=", state])
url_list.append("#wechat_redirect")
return "".join(url_list)
示例5: get_authorize_url
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def get_authorize_url(self, redirect_uri, scope="snsapi_base", state=""):
"""
:param redirect_uri: 重定向地址,需要urlencode,這裏填寫的應是服務開發方的回調地址
:param scope: 可選,微信公眾號 OAuth2 scope,默認為 ``snsapi_base``
:param state: 可選,重定向後會帶上state參數,開發者可以填寫任意參數值,最多128字節
"""
redirect_uri = quote(redirect_uri, safe=b"")
url_list = [
self.OAUTH_BASE_URL,
"oauth2/authorize?appid=",
self.app_id,
"&redirect_uri=",
redirect_uri,
"&response_type=code&scope=",
scope,
]
if state:
url_list.extend(["&state=", state])
url_list.extend(
["&component_appid=", self.component.component_appid,]
)
url_list.append("#wechat_redirect")
return "".join(url_list)
示例6: test_query_string_decoding
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def test_query_string_decoding(self):
URI_TMPL = '/reqparams?q={q}'
europoundUtf8_2_bytes = europoundUnicode.encode('utf-8')
europoundUtf8_2nd_byte = europoundUtf8_2_bytes[1:2]
# Encoded utf8 query strings MUST be parsed correctly.
# Here, q is the POUND SIGN U+00A3 encoded in utf8 and then %HEX
self.getPage(URI_TMPL.format(q=url_quote(europoundUtf8_2_bytes)))
# The return value will be encoded as utf8.
self.assertBody(b'q: ' + europoundUtf8_2_bytes)
# Query strings that are incorrectly encoded MUST raise 404.
# Here, q is the second byte of POUND SIGN U+A3 encoded in utf8
# and then %HEX
# TODO: check whether this shouldn't raise 400 Bad Request instead
self.getPage(URI_TMPL.format(q=url_quote(europoundUtf8_2nd_byte)))
self.assertStatus(404)
self.assertErrorPage(
404,
'The given query string could not be processed. Query '
"strings for this resource must be encoded with 'utf8'.")
示例7: format_image_html
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def format_image_html(img_ext, byte_arr):
if img_ext == "jpg":
img_ext = "JPEG"
elif img_ext == "jpeg":
img_ext = "JPEG"
elif img_ext == "png":
img_ext = "PNG"
raw_base = encode_b64(byte_arr)
encoded = []
i = 0
begin = i * 72
end = i * 72
mid_raw_base = mid(raw_base, begin, 72)
encoded.append(quote(mid_raw_base, safe=''))
i += 1
while end < len(raw_base):
begin = i * 72
end = i * 72
mid_raw_base = mid(raw_base, begin, 72)
encoded.append(quote(mid_raw_base, safe=''))
i += 1
return f"<img src='data:image/{img_ext};base64,{''.join(encoded)}' />"
示例8: test_redirect_with_params
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def test_redirect_with_params(app, test_str):
use_in_uri = quote(test_str)
@app.route("/api/v1/test/<test>/")
async def init_handler(request, test):
return redirect(f"/api/v2/test/{use_in_uri}/")
@app.route("/api/v2/test/<test>/")
async def target_handler(request, test):
assert test == test_str
return text("OK")
_, response = app.test_client.get(f"/api/v1/test/{use_in_uri}/")
assert response.status == 200
assert response.content == b"OK"
示例9: validate_
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def validate_(self, value, context=None):
url = self.valid_url(value)
if not url:
raise StopValidationError(self.messages['invalid_url'])
if self.verify_exists:
url_string = urlquote(urlunsplit((
url['scheme'],
(url['host6'] or url['host4'] or url['hostn_enc']) + ':' + (url['port'] or ''),
url['path'],
url['query'],
url['frag'])
).encode('utf-8'), safe=VALID_CHAR_STRING)
try:
urlopen(url_string)
except URLError:
raise StopValidationError(self.messages['not_found'])
示例10: _get_proxy_info
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def _get_proxy_info(context):
if not context.get('proxy_hostname') or not context.get('proxy_port'):
return None
user_pass = ''
if context.get('proxy_username') and context.get('proxy_password'):
username = quote(context['proxy_username'], safe='')
password = quote(context['proxy_password'], safe='')
user_pass = '{user}:{password}@'.format(
user=username, password=password)
proxy = 'http://{user_pass}{host}:{port}'.format(
user_pass=user_pass, host=context['proxy_hostname'],
port=context['proxy_port'])
proxies = {
'http': proxy,
'https': proxy,
}
return proxies
示例11: __init__
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def __init__(self, search):
"""初始化,也就是模糊搜索的第一步
:param search: 關鍵字
"""
self.header = {'User-Agent': random()} # 設置UA
# 將中文字轉化為URL鏈接。注意搜狗將中文字進行的GBK編碼。而不是UTF-8
url_word = quote(search.encode('GBK'))
url = 'https://pinyin.sogou.com/dict/search/search_list/%s/normal/' % url_word # 搜索鏈接
response = requests.get(url=url, headers=self.header)
match = re.findall(url[24:] + '(.{1,3})">', response.text) # 匹配下載頁數
max_page = max(map(lambda x: int(x), match)) if match else 1 # 選取最大的頁數,如果沒有頁數返回1
m = [] # 將匹配到下載鏈接
for page in range(1, max_page + 1):
response = requests.get(url=url + str(page), headers=self.header)
match = re.findall(r'id=(.+)&name=(.+)"', response.text) # 匹配下載鏈接
m.extend(match) # 將匹配到的下載鏈接裝到鏈表中
load_url = 'https://pinyin.sogou.com/d/dict/download_cell.php?id={0}&name={1}' # 下載鏈接的格式
# 將匹配到的,名字和ID映射到下載鏈接格式中
self.load_url = map(lambda x: load_url.format(x[0], x[1]), m)
示例12: math_tex
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def math_tex(tex, file_path=None):
"""根據Tex語言生成數學公式矢量圖
關於Tex語法參考:https://blog.csdn.net/qfire/article/details/81382048
:param tex: Tex語言
:param file_path: 保存矢量圖的地址,後綴名一定是: xxx.svg
:return: 默認返回SVG數據。有地址保存到地址,返回True
"""
u = quote(tex)
name = hash(tex)
s = get(f'https://math.jianshu.com/math?formula={u}')
data = s.text
if not file_path:
file_path = './' + str(name) + '.svg'
w = open(file_path, 'w')
w.write(data)
w.flush()
w.close()
return True
示例13: diff_toDelta
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def diff_toDelta(self, diffs):
"""Crush the diff into an encoded string which describes the operations
required to transform text1 into text2.
E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
Operations are tab-separated. Inserted text is escaped using %xx notation.
Args:
diffs: Array of diff tuples.
Returns:
Delta text.
"""
text = []
for (op, data) in diffs:
if op == self.DIFF_INSERT:
# High ascii will raise UnicodeDecodeError. Use Unicode instead.
data = data.encode("utf-8")
text.append("+" + parse.quote(data, "!~*'();/?:@&=+$,# "))
elif op == self.DIFF_DELETE:
text.append("-%d" % len(data))
elif op == self.DIFF_EQUAL:
text.append("=%d" % len(data))
return "\t".join(text)
示例14: get_download_link
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def get_download_link(book_id, book_format, client):
book_format = book_format.split(".")[0]
book = calibre_db.get_filtered_book(book_id)
if book:
data1 = calibre_db.get_book_format(book.id, book_format.upper())
else:
abort(404)
if data1:
# collect downloaded books only for registered user and not for anonymous user
if current_user.is_authenticated:
ub.update_download(book_id, int(current_user.id))
file_name = book.title
if len(book.authors) > 0:
file_name = book.authors[0].name + '_' + file_name
file_name = get_valid_filename(file_name)
headers = Headers()
headers["Content-Type"] = mimetypes.types_map.get('.' + book_format, "application/octet-stream")
headers["Content-Disposition"] = "attachment; filename=%s.%s; filename*=UTF-8''%s.%s" % (
quote(file_name.encode('utf-8')), book_format, quote(file_name.encode('utf-8')), book_format)
return do_download_file(book, book_format, client, data1, headers)
else:
abort(404)
示例15: upload_video
# 需要導入模塊: from urllib import parse [as 別名]
# 或者: from urllib.parse import quote [as 別名]
def upload_video(video_dict, user_config):
upload_way_dict = {'bd': BDUpload,
's3': S3Upload}
upload_way = upload_way_dict.get(config['upload_by'])
uploader = upload_way()
ddir = get_ddir(user_config)
uploader.upload_item(f"{ddir}/{video_dict['Title']}", video_dict['Title'])
if config['upload_by'] == 'bd':
share_url = uploader.share_item(video_dict['Title'])
if config['enable_mongodb']:
db = Database(user_map(video_dict['User']))
db.insert(video_dict['Title'], share_url, video_dict['Date'])
elif config['upload_by'] == 's3':
if config['enable_mongodb']:
db = Database(user_map(video_dict['User']))
db.insert(video_dict['Title'],
f"gets3/{quote(video_dict['Title'])}",
video_dict['Date'])
else:
raise RuntimeError(f'Upload {video_dict["Title"]} failed')
bot(f"[下載提示] {video_dict['Title']} 已上傳, 請查看https://matsuri.design/", user_config)