Beispiel #1
0
    def quote(content, safe='/', encoding=None, errors=None):
        """ Replaces single character non-ascii characters and URI specific
        ones by their %xx code.

        Wrapper to Python's unquote while remaining compatible with both
        Python 2 & 3 since the reference to this function changed between
        versions.

        Args:
            content (str): The URI string you wish to quote
            safe (str): non-ascii characters and URI specific ones that you
                        do not wish to escape (if detected). Setting this
                        string to an empty one causes everything to be
                        escaped.
            encoding (:obj:`str`, optional): encoding type
            errors (:obj:`str`, errors): how to handle invalid character found
                in encoded string (defined by encoding)

        Returns:
            str: The quoted URI string
        """
        if not content:
            return ''

        try:
            # Python v3.x
            return _quote(content, safe=safe, encoding=encoding, errors=errors)

        except TypeError:
            # Python v2.7
            return _quote(content, safe=safe)
Beispiel #2
0
    def quote(content, safe='/', encoding=None, errors=None):
        """
        common quote function

        """
        if not content:
            return ''

        try:
            # Python v3.x
            return _quote(content, safe=safe, encoding=encoding, errors=errors)

        except TypeError:
            # Python v2.7
            return _quote(content, safe=safe)
Beispiel #3
0
def quote(value, safe='/'):
    """
    Patched version of urllib.quote that encodes utf8 strings before quoting
    """
    if isinstance(value, unicode):
        value = value.encode('utf8')
    return _quote(value, safe)
Beispiel #4
0
def quote(s, safe=b'/'):
    s = _quote(s.encode('utf-8'), safe)
    # PY3 always returns unicode.  PY2 may return either, depending on whether
    # it had to modify the string.
    if isinstance(s, bytes_type):
        s = s.decode('utf-8')
    return s
Beispiel #5
0
 def genQrcode (self,NoLIMIT = False, **kwargs):
     u'''指定是创建临时False,[senceId,exp_sec]还是永久True,[senceId],二维码,以及场景ID.
     正确返回URL,错误返回None/抛出异常 ValueError WechatError
     http://mp.weixin.qq.com/wiki/index.php?title=%E7%94%9F%E6%88%90%E5
     %B8%A6%E5%8F%82%E6%95%B0%E7%9A%84%E4%BA%8C%E7%BB%B4%E7%A0%81'''
     PURL = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s' % self.ACCESS_TOKEN()
     if NoLIMIT:
         if args[0] not in range(1,100001):
             raise ValueError(u'参数不符合要求')
         jsData = u'{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": %d}}}' % kwargs.get('senceId')
     else:
         exp_sec,tmpId = kwargs.get('exp_sec'),kwargs.get('senceId')
         if (exp_sec not in range(10,1801)) or (tmpId > 4294967296) :
             raise ValueError(u'参数不符合要求')
         jsData = u'{"expire_seconds": %d, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": %d}}}' % (exp_sec, tmpId)
     try:
         resObj = rst.post(PURL, jsData)
         if  json.loads(resObj.text, resObj.encoding).get(u"errcode"):
             raise WeChatError(resObj.text)        
     except ValueError:
         raise  WXError(u'服务器数据错误,[%s]')
     except Exception:
         log.error(u'上传文件时出错')
         raise WXError(NetworkError.ERR_INTERNET_INVAILD)  
     ticket = _quote(json.loads(resObj.text, resObj.encoding).get(u'ticket'))#创建二维码ticket
     GURL = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + ticket
     #凭借ticket到指定URL换取二维码,返回地址,自行决定是分发URL还是下载
     return GURL
Beispiel #6
0
def quote(s, safe=b'/'):
    s = _quote(s, safe)
    # PY3 always returns unicode.  PY2 may return either, depending on whether
    # it had to modify the string.
    if isinstance(s, bytes_type):
        s = s.decode('utf-8')
    return s
Beispiel #7
0
def quote(value, safe="/"):
    """
    Patched version of urllib.quote that encodes utf8 strings before quoting
    """
    if isinstance(value, unicode):
        value = value.encode("utf8")
    return _quote(value, safe)
Beispiel #8
0
def quote(resource):
    """
    This implementation of urllib.quote supports all unicode characters

    :param: resource: Resource value to be url encoded.
    """
    return _quote(
        resource.encode('utf-8') if isinstance(resource, str) else resource, )
Beispiel #9
0
def quote(s, safe=b"/"):
    s = s.encode("utf-8") if isinstance(s, unicode_type) else s
    s = _quote(s, safe)
    # PY3 always returns unicode.  PY2 may return either, depending on whether
    # it had to modify the string.
    if isinstance(s, bytes_type):
        s = s.decode("utf-8")
    return s
Beispiel #10
0
def quote(string):
    try:
        if type(string) is unicode:
            string = string.encode('utf-8')
        return _quote(string)
    except:
        print 'quoted string is:', string
        raise
Beispiel #11
0
def quote(s, safe=b"/"):
    s = s.encode("utf-8") if isinstance(s, unicode_type) else s
    s = _quote(s, safe)
    # PY3 always returns unicode.  PY2 may return either, depending on whether
    # it had to modify the string.
    if isinstance(s, bytes):
        s = s.decode("utf-8")
    return s
Beispiel #12
0
def quote(value, safe='/'):
    """
    Patched version of urllib.quote that encodes utf8 strings before quoting
    """
    value = encode_utf8(value)
    if isinstance(value, str):
        return _quote(value, safe)
    else:
        return value
Beispiel #13
0
def quote(value, safe='/'):
    """
    Patched version of urllib.quote that encodes utf8 strings before quoting
    """
    value = encode_utf8(value)
    if isinstance(value, str):
        return _quote(value, safe)
    else:
        return value
Beispiel #14
0
def quote(resource, safe='/', encoding=None, errors=None):
    """
    This implementation of urllib.quote supports all unicode characters

    :param: resource: Resource value to be url encoded.
    """
    return _quote(
        resource.encode('utf-8') if isinstance(resource, str) else resource,
        safe=safe, encoding=encoding,
        errors=errors,
    )
Beispiel #15
0
def quote(text, *args, **kwargs):
    t = type(text)
    if t is str:
        converted_text = text
    elif t is unicode:
        converted_text = str(text.encode('utf-8'))
    else:
        try:
            converted_text = str(text)
        except:
            converted_text = text
    return _quote(converted_text, *args, **kwargs)
Beispiel #16
0
def quote(text, *args, **kwargs):
	t = type(text)
	if t is str:
		converted_text = text
	elif t is unicode:
		converted_text = str(text.encode('utf-8'))
	else:
		try:
			converted_text = str(text)
		except:
			converted_text = text
	return _quote(converted_text, *args, **kwargs)
Beispiel #17
0
def quote(name):
    """Extended quote for the DAP spec.

    The period MUST be escaped in names (DAP spec, item 5.1):

        >>> quote("White space")
        'White%20space'
        >>> _quote("Period.")
        'Period.'
        >>> quote("Period.")
        'Period%2E'
    """
    return _quote(name).replace('.', '%2E')
Beispiel #18
0
def quote(name):
    """Extended quote for the DAP spec.

    The period MUST be escaped in names (DAP spec, item 5.1):

        >>> quote("White space")
        'White%20space'
        >>> _quote("Period.")
        'Period.'
        >>> quote("Period.")
        'Period%2E'
    """
    return _quote(name).replace('.', '%2E')
Beispiel #19
0
def quote(value, safe='/'):
    if isinstance(value, unicode):
        (value, _len) = utf8_encoder(value, 'replace')
    (valid_utf8_str, _len) = utf8_decoder(value, 'replace')
    return _quote(valid_utf8_str.encode('utf-8'), safe)
Beispiel #20
0
def q(value, safe='/'):
    value = encode_utf8(value)
    if isinstance(value, str):
        return _quote(value, safe)
    else:
        return value
Beispiel #21
0
def quote(value, safe='/'):
    if isinstance(value, unicode):
        value = value.encode('utf8')
    return _quote(value, safe)
Beispiel #22
0
import re, os, sys, subprocess, copy, traceback, logging

try:
    from HTMLParser import HTMLParser
except ImportError:
    from html.parser import HTMLParser
try:
    from urllib import quote as _quote
    quote = lambda n: _quote(n.encode('utf8', 'replace'))
except ImportError:
    from urllib.parse import quote

import requests

from . import config

logger = logging.getLogger('itchat')

emojiRegex = re.compile(r'<span class="emoji emoji(.{1,10})"></span>')
htmlParser = HTMLParser()
try:
    b = u'\u2588'
    sys.stdout.write(b + '\r')
    sys.stdout.flush()
except UnicodeEncodeError:
    BLOCK = 'MM'
else:
    BLOCK = b
friendInfoTemplate = {}
for k in ('UserName', 'City', 'DisplayName', 'PYQuanPin', 'RemarkPYInitial', 'Province',
        'KeyWord', 'RemarkName', 'PYInitial', 'EncryChatRoomId', 'Alias', 'Signature', 
Beispiel #23
0
def quote(*l):
    return tuple(_quote(unicodeToStr(s))
                 for s in l) if len(l) != 1 else _quote(unicodeToStr(l[0]))
Beispiel #24
0
 def quote(p, *args, **kwargs):
     return _quote(_reencode(p), *args, **kwargs)
Beispiel #25
0
def quote(s):
    quoted = _quote(s)
    if isinstance(quoted, unicode):
        quoted = quoted.encode("ascii")
    return quoted
Beispiel #26
0
def q(value, safe='/'):
    value = encode_utf8(value)
    if isinstance(value, str):
        return _quote(value, safe)
    else:
        return value
Beispiel #27
0
def _genViewTypeJson(name, url):
    if len(name.encode('utf8')) >16:
        raise ValueError(u'名字太长,建议小于8个汉字,16字节')
    if len(_quote(url)) > 256:
        raise ValueError(u'URL太长,需要小于256字节')
    return u'{"type":"view", "name":"%s", "url": "%s"}' % (unicode(name), url)
Beispiel #28
0
def quote(s):
    return networkString(_quote(s))
Beispiel #29
0
def  _genClickTypeJson(name, key):
    if len(name.encode('utf8')) >16:
        raise ValueError(u'名字太长,建议小于8个汉字,16字节')
    if len(_quote(key)) > 128:
        raise ValueError(u'KEY太长,需要小于128字节')
    return u'{"type":"click", "name":"%s", "key": "%s"}' % (unicode(name), key)
Beispiel #30
0
 def quote(s, safe='/'):
     safe = safe.encode('utf-8')
     s = s.encode('utf-8')
     return _quote(s, safe)
Beispiel #31
0
def quote(*l):
    return tuple(_quote(unicodeToStr(s)) for s in l) if len(l) != 1 else _quote(unicodeToStr(l[0]))
Beispiel #32
0
calc.py - Sopel Calculator Module
Copyright 2008, Sean B. Palmer, inamidst.com
Licensed under the Eiffel Forum License 2.

https://sopel.chat
"""
from __future__ import unicode_literals, absolute_import, print_function, division

from sopel.module import commands, example
from sopel.tools.calculation import eval_equation
from requests import get
import sys

if sys.version_info.major < 3:
    from urllib import quote as _quote
    quote = lambda s: _quote(s.encode('utf-8')).decode('utf-8')
else:
    from urllib.parse import quote

if sys.version_info.major >= 3:
    unichr = chr

BASE_TUMBOLIA_URI = 'https://tumbolia-sopel.appspot.com/'


@commands('c', 'calc')
@example('.c 5 + 3', '8')
@example('.c 0.9*10', '9')
@example('.c 10*0.9', '9')
@example('.c 2*(1+2)*3', '18')
@example('.c 2**10', '1024')
def quote(value, safe='/'):
    """
    Patched version of urllib.quote that encodes utf-8 strings before quoting
    """
    return _quote(get_valid_utf8_str(value), safe)
Beispiel #34
0
def quote(value, safe='/'):
    if isinstance(value, unicode):
        value = value.encode('utf8')
    return _quote(value, safe)
Beispiel #35
0
 def quote(s, safe="/"):  # type: (str, str) -> str
     safe = safe.encode("utf-8")
     s = s.encode("utf-8")
     return _quote(s, safe)
Beispiel #36
0
def quote(string):
    assert(type(string) in [unicode, str])
    return _quote(string.encode('utf-8')) if isinstance(string, unicode) else _quote(string)
Beispiel #37
0
def quote(_i):
    return _quote(_i, "")
Beispiel #38
0
 def quote(s):
     return _quote(s.encode('utf-8')).decode('utf-8')
Beispiel #39
0
# Copyright 2011, Toru Maesaka
#
# Redistribution and use of this source code is licensed under
# the BSD license. See COPYING file for license description.

import base64
import httplib
import struct
import time
import kt_error
try:
    from percentcoding import quote, unquote
except ImportError:
    from urllib import quote as _quote
    from urllib import unquote
    quote = lambda s: _quote(s, safe="")

try:
    import cPickle as pickle
except ImportError:
    import pickle

# Stick with URL encoding for now. Eventually run a benchmark
# to evaluate what the most approariate encoding algorithm is.
KT_HTTP_HEADER = {
    'Content-Type': 'text/tab-separated-values; colenc=U',
}

KT_PACKER_CUSTOM = 0
KT_PACKER_PICKLE = 1
KT_PACKER_JSON = 2
Beispiel #40
0
def quote(s):
    return networkString(_quote(s))
Beispiel #41
0
def quote(string):
    assert (type(string) in [unicode, str])
    return _quote(string.encode('utf-8')) if isinstance(
        string, unicode) else _quote(string)
Beispiel #42
0
def quote(value, safe='/'):
    """Patched version of urllib.quote that UTF8 encodes unicode."""
    if isinstance(value, unicode):
        value = value.encode('utf8')
    return _quote(value, safe)
Beispiel #43
0
def quote(s, safe=b'/'):
    return to_unicode(_quote(to_bytes(s), safe))
Beispiel #44
0
def quote(value, safe='/'):
    if isinstance(value, unicode):
        (value, _len) = utf8_encoder(value, 'replace')
    (valid_utf8_str, _len) = utf8_decoder(value, 'replace')
    return _quote(valid_utf8_str.encode('utf-8'), safe)
Beispiel #45
0
def quote(url):
    if PY3:
        return _quote(bytes(u(url), encoding="utf-8"))
    return _quote(u(url))
try:
    import httplib
except ImportError:
    import http.client as httplib

try:
    from urllib import quote as _quote
    from urllib import quote as _quote_from_bytes
    from urllib import unquote as unquote_to_bytes
except ImportError:
    from urllib.parse import quote as _quote
    from urllib.parse import quote_from_bytes as _quote_from_bytes
    from urllib.parse import unquote_to_bytes

quote = lambda s: _quote(s, safe='')
quote_from_bytes = lambda s: _quote_from_bytes(s, safe='')

try:
    import cPickle as pickle
except ImportError:
    import pickle

import json

KT_HTTP_HEADER = {'Content-Type' : 'text/tab-separated-values; colenc=U'}

def _dict_to_tsv(kv_dict):
    lines = []
    for k, v in kv_dict.items():
        quoted = quote_from_bytes(v) if isinstance(v, bytes) else quote(str(v))
Beispiel #47
0
def quote(s, safe='/'):
    if isinstance(s, unicode):
        s = s.encode('utf-8', 'ignore') # hope we're using utf-8!
    return _quote(s, safe).replace('/', encoded_slash)
Beispiel #48
0
calc.py - Sopel Calculator Module
Copyright 2008, Sean B. Palmer, inamidst.com
Licensed under the Eiffel Forum License 2.

https://sopel.chat
"""
from __future__ import unicode_literals, absolute_import, print_function, division

from sopel.module import commands, example
from sopel.tools.calculation import eval_equation
from requests import get
import sys

if sys.version_info.major < 3:
    from urllib import quote as _quote
    quote = lambda s: _quote(s.encode('utf-8')).decode('utf-8')
else:
    from urllib.parse import quote

if sys.version_info.major >= 3:
    unichr = chr


BASE_TUMBOLIA_URI = 'https://tumbolia-sopel.appspot.com/'


@commands('c', 'calc')
@example('.c 5 + 3', '8')
@example('.c 0.9*10', '9')
@example('.c 10*0.9', '9')
@example('.c 2*(1+2)*3', '18')
Beispiel #49
0
 def quote(string, safe=b'/'):
     if not isinstance(safe, bytes):
         safe = safe.encode('ascii', 'ignore')
     if not isinstance(string, bytes):
         string = string.encode('utf8')
     return _quote(string, safe)
Beispiel #50
0
import re, os, sys, subprocess, copy, traceback, logging

try:
    from HTMLParser import HTMLParser
except ImportError:
    from html.parser import HTMLParser
try:
    from urllib import quote as _quote
    quote = lambda n: _quote(n.encode('utf8', 'replace'))
except ImportError:
    from urllib.parse import quote

import requests

from . import config

logger = logging.getLogger('itchat')

emojiRegex = re.compile(r'<span class="emoji emoji(.{1,10})"></span>')
htmlParser = HTMLParser()
try:
    b = u'\u2588'
    sys.stdout.write(b + '\r')
    sys.stdout.flush()
except UnicodeEncodeError:
    BLOCK = 'MM'
else:
    BLOCK = b
friendInfoTemplate = {}
for k in ('UserName', 'City', 'DisplayName', 'PYQuanPin', 'RemarkPYInitial',
          'Province', 'KeyWord', 'RemarkName', 'PYInitial', 'EncryChatRoomId',
Beispiel #51
0
# Copyright 2011, Toru Maesaka
#
# Redistribution and use of this source code is licensed under
# the BSD license. See COPYING file for license description.

import base64
import httplib
import struct
import time
import kt_error
try:
    from percentcoding import quote, unquote
except ImportError:
    from urllib import quote as _quote
    from urllib import unquote
    quote = lambda s: _quote(s, safe="")

try:
    import cPickle as pickle
except ImportError:
    import pickle

# Stick with URL encoding for now. Eventually run a benchmark
# to evaluate what the most approariate encoding algorithm is.
KT_HTTP_HEADER = {
  'Content-Type' : 'text/tab-separated-values; colenc=U',
}

KT_PACKER_CUSTOM = 0
KT_PACKER_PICKLE = 1
KT_PACKER_JSON   = 2
Beispiel #52
0
 def quote(s):
     if isinstance(s, unicode):
         s = s.encode('utf-8')
     return _quote(s)
Beispiel #53
0
def quote(value):
    value = value.encode('utf8', errors='ignore') if isinstance(value, unicode) else str(value)
    return _quote(value, safe='')
Beispiel #54
0
 def quote(s):
     if isinstance(s, unicode):
         s = s.encode('utf-8')
     return _quote(s)
Beispiel #55
0
 def quote(p, *args, **kwargs):
     return _quote(_reencode(p), *args, **kwargs)