def request_ocr_service_base64(self, uri, imagepath, options=None):
        """
        :param uri: URI for the HTTP request to be called
        :param imagepath: full path or URL of the image to be recognized
        :param options: optional parameter in the HTTP request of OCR
        :return:None
        """
        if imagepath == "" or uri == "":
            raise ValueError(
                "The parameter for requestOcrServiceBase64 cannot be empty.")
        request = signer.HttpRequest()
        request.scheme = self.httpschema
        request.host = self.endpoint
        request.method = self.httpmethod
        request.uri = uri
        request.headers = {"Content-Type": "application/json"}

        body = {}
        if "http://" in imagepath or "https://" in imagepath:
            body["url"] = imagepath
        else:
            with open(imagepath, "rb") as f:
                img = f.read()
            img_base64 = base64.b64encode(img).decode("utf-8")
            body["image"] = img_base64
            if options:
                body.update(options)
            request.body = json.dumps(body)
        self.sig.Sign(request)
        url = self.httpschema + "://" + self.endpoint + uri
        response = requests.post(url,
                                 data=request.body,
                                 headers=request.headers)
        return response
Exemple #2
0
 def request_ocr_service_base64(self,uri, filepath, options=None):
     """
     :param uri: the uri for the http request to be called
     :param filepath: the fullpath of the file to be recognized
     :param options: optional parameter in the ocr http request
     :return:None
     """
     if filepath == "" or uri == "":
         raise ValueError("the parameter for requestOcrServiceBase64 cannot be empty")
     request=signer.HttpRequest()
     request.scheme=self.httpschema
     request.host=self.endpoint
     request.method=self.httpmethod
     request.uri=uri
     request.headers={"Content-Type": "application/json"}
     with open(filepath, 'rb') as f:
         img = f.read()
     img_base64 = base64.b64encode(img).decode("utf-8")
     body = {}
     body['image'] = img_base64
     if options:
         body.update(options)
     request.body=json.dumps(body)
     self.sig.Sign(request)
     url = self.httpschema+"://"+self.endpoint+uri
     #response=requests.request(self.httpmethod,url,data=request.body,headers=request.headers)
     response = requests.post(url, data=request.body, headers=request.headers)
     return response
Exemple #3
0
    def _get_response(self, methed, host, uri, header, query=None, body=None):

        sig = signer.Signer()
        # Set the AK/SK to sign and authenticate the request.
        sig.Key = self.__access
        sig.Secret = self.__secret
        # The following example shows how to set the request URL and parameters to query a VPC list.
        r = signer.HttpRequest()
        r.scheme = "https"
        # Set request Endpoint.
        r.host = host
        # Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
        r.method = methed
        # Set request URI.
        r.uri = uri
        # Set parameters for the request URL.
        r.query = query
        # Add header parameters, for example, x-domain-id for invoking a global service and x-project-id for invoking a project-level service.
        r.headers = header
        if body is not None:
            r.body = body
        sig.Sign(r)

        if self.__securitytoken is not None:
            r.headers['X-Security-Token'] = self.__securitytoken

        httpclient = HttpClient(host=r.host,
                                url=r.uri,
                                method=r.method,
                                headers=r.headers,
                                body=r.body,
                                timeout=self._connect_timeout)
        return httpclient.get_https_response()
        def wrapped(*args, **kwargs):
            if "authorization" not in request.headers:
                return 'Authorization not found.', 401
            authorization = request.headers['authorization']
            m = authorizationPattern.match(authorization)
            if m is None:
                return 'Authorization format incorrect.', 401
            signingKey = m.group(1)
            if signingKey not in secrets:
                return 'Signing key not found.', 401
            signingSecret = secrets[signingKey]
            signedHeaders = m.group(2).split(";")
            r = signer.HttpRequest()
            r.method = request.method
            r.uri = request.path
            r.query = {}
            for k in request.query_string.decode('utf-8').split('&'):
                spl = k.split("=", 1)
                if spl[0] != "":
                    if len(spl) < 2:
                        r.query[spl[0]] = ""
                    else:
                        r.query[spl[0]] = spl[1]

            r.headers = {}
            needbody = True
            dateHeader = None
            for k in signedHeaders:
                if k not in request.headers:
                    return 'Signed header ' + k + ' not found', 401
                v = request.headers[k]
                if k.lower(
                ) == 'x-sdk-content-sha256' and v == 'UNSIGNED-PAYLOAD':
                    needbody = False
                if k.lower() == 'x-sdk-date':
                    dateHeader = v
                r.headers[k] = v
            if needbody:
                r.body = request.get_data()

            if dateHeader is None:
                return 'Header x-sdk-date not found.', 401
            t = datetime.strptime(dateHeader, BasicDateFormat)
            if abs(t - datetime.utcnow()) > timedelta(minutes=15):
                return 'Signature expired.', 401

            sig = signer.Signer()
            sig.Key = signingKey
            sig.Secret = signingSecret
            if not sig.Verify(r, m.group(3)):
                return 'Verify authroization failed.', 401
            return f(*args, **kwargs)
Exemple #5
0
def httpSign():
    sig = signer.Signer()
    sig.Key = '0CJLRMLEUJXDGMCQPOYK'
    sig.Secret  = 'hfpIkt4ZZFqYlpqnV7H1BiEFSNDsSUel1CFsc8GQ'

    url = "https://cbs-ext.cn-north-4.myhuaweicloud.com/v1/06e34d38048026b52f94c01d8ff43e1c/qabots/4c0a16c6-5176-4938-bfb5-1d5546ece167/chat"
   
    headers = {
        'Content-Type': 'application/json', 
        'X-Sdk-Content-Sha256' : 'UNSIGNED-PAYLOAD'
    }
    
    r = signer.HttpRequest("POST", url=url, headers = headers)
    sig.Sign(r)
    return r
    def call(cls, *args):
        if not cls._singleton:
            cls._singleton = cls()

        cls._singleton.construct_querystring(*args)
        request_url = f'{cls._singleton.__class__.url_base}{cls._singleton.canonical_uri}'
        if cls._singleton.canonical_qs:
            request_url = f'{request_url}?{cls._singleton.canonical_qs}'

        r = signer.HttpRequest(cls._singleton.http_method, request_url)
        sig.Sign(r)
        r.headers['X-Project-Id'] = project_id
        # If uri already takes query string, then don't pass r.query to 'params' argument
        # or it will be handled twice, the value becomes a list with 2 same elements.
        res = requests.request(r.method, request_url, headers=r.headers, data=r.body)
        return res.json()
Exemple #7
0
    async def _req(self, method, url, data):
        r = signer.HttpRequest(method, url)
        r.headers = {'content-type': 'application/json'}
        if isinstance(data, dict):
            data = json.dumps(data)
        r.body = data
        self._sig.Sign(r)

        async with ClientSession() as session:
            session: ClientSession
            async with session.request(r.method,
                                       r.scheme + '://' + r.host + r.uri,
                                       headers=r.headers,
                                       data=r.body) as resp:
                resp: ClientResponse
                print(resp.request_info.url)
                if resp.status < 200 or resp.status >= 300:
                    print(resp.status, resp.reason)
                    text = await resp.text()
                    print(f'error = {text}')
                return await resp.json()
Exemple #8
0
# coding=utf-8
import requests
from apig_sdk import signer

if __name__ == '__main__':
    sig = signer.Signer()
    sig.Key = "bbeed2b5-8b7f-44d2-8ae1-3d7a78b5b249"
    sig.Secret = "52cf34a05b4c3cfd467fc60c6a9571bd3a3b19d5d12d93b3860f72b582551567"

    r = signer.HttpRequest(
        "GET",
        #"https://29c8bf7004354c28a8ece1e9db45d710.apic.cn-east-2.huaweicloudapis.com/test",
        "https://3d98f804db0e4fb4bb32677f973c3d44.apic.cn-east-2.huaweicloudapis.com/testA",
        {"x-stage": "RELEASE"},
        "body")
    sig.Sign(r)
    print(r.headers["X-Sdk-Date"])
    print(r.headers["Authorization"])
    resp = requests.request(r.method,
                            r.scheme + "://" + r.host + r.uri,
                            headers=r.headers,
                            data=r.body)
    print(resp.status_code, resp.reason)
    print(resp.content)
Exemple #9
0
import requests
from apig_sdk import signer

if __name__ == '__main__':
    sig = signer.Signer()
    # Set the AK/SK to sign and authenticate the request.
    sig.Key = "WBLMIQTE4GXRCAUP5KM6"
    sig.Secret = "KjuMhKO93QLhWUfROouNo3AxZNKPuwTGEglMQ3hR"

    # The following example shows how to set the request URL and parameters to query a VPC list.
    # Set request Endpoint.
    # Specify a request method, such as GET, PUT, POST, DELETE, HEAD, and PATCH.
    # Set request URI.
    # Set parameters for the request URL.
    r = signer.HttpRequest(
        "GET",
        "https://console.huaweicloud.com/mc/?region=cn-north-4&locale=zh-cn#/mc/messages/83b0fc849eb8408c9e66954398510f86"
    )
    # Add header parameters, for example, x-domain-id for invoking a global service and x-project-id for invoking a project-level service.
    r.headers = {"content-type": "application/json"}
    # Add a body if you have specified the PUT or POST method. Special characters, such as the double quotation mark ("), contained in the body must be escaped.
    r.body = ""
    sig.Sign(r)
    print(r.headers["X-Sdk-Date"])
    print(r.headers["Authorization"])
    resp = requests.request(r.method,
                            r.scheme + "://" + r.host + r.uri,
                            headers=r.headers,
                            data=r.body)
    print(resp.status_code, resp.reason)
    print(resp.content)
    print(resp.text)
Exemple #10
0
from apig_sdk import signer
import requests

sig = signer.Signer()
# Set the AK/SK to sign and authenticate the request.
sig.Key = ""
sig.Secret = ""

# The following example shows how to set the request URL and parameters to query a VPC list.
r = signer.HttpRequest(
    "GET",
    "https://vpc.my-kualalumpur-1.alphaedge.tmone.com.my/v1/{ProjectID}/vpcs?limit=10"
)
r.headers = {"content-type": "application/json"}
sig.Sign(r)
resp = requests.request(r.method,
                        r.scheme + "://" + r.host + r.uri,
                        headers=r.headers,
                        data=r.body)
print(resp.status_code, resp.reason)
print(resp.content)

# The following example shows how to set the request URL and parameters to query a ECSs list.
r = signer.HttpRequest(
    "GET",
    "https://ecs.my-kualalumpur-1.alphaedge.tmone.com.my/v2/{ProjectID}/servers"
)
r.headers = {"content-type": "application/json"}
sig.Sign(r)
resp = requests.request(r.method,
                        r.scheme + "://" + r.host + r.uri,
Exemple #11
0
# coding=utf-8
import requests
from apig_sdk import signer

if __name__ == '__main__':
    sig = signer.Signer()
    sig.Key = "apigateway_sdk_demo_key"
    sig.Secret = "apigateway_sdk_demo_secret"

    r = signer.HttpRequest(
        "POST",
        "https://30030113-3657-4fb6-a7ef-90764239b038.apigw.cn-north-1.huaweicloud.com/app1?a=1",
        {"x-stage": "RELEASE"}, "body")
    sig.Sign(r)
    print(r.headers["X-Sdk-Date"])
    print(r.headers["Authorization"])
    resp = requests.request(r.method,
                            r.scheme + "://" + r.host + r.uri,
                            headers=r.headers,
                            data=r.body)
    print(resp.status_code, resp.reason)
    print(resp.content)
Exemple #12
0
# coding=utf-8
import sys
import requests
from apig_sdk import signer

if sys.version_info.major < 3:
    from urllib import quote
else:
    from urllib.parse import quote

if __name__ == '__main__':
    sig = signer.Signer()
    sig.Key = "725e57fd-09fa-454b-bf37-ad41190b660c-c6adbafd-9420-49b1-9d91-905bd70ce6de"
    sig.Secret = "25EF9023B9AF78EDE2136C95EA44A764"

    r = signer.HttpRequest()
    r.scheme = "http"
    r.host = "192.168.36.144"
    r.method = "GET"
    #uri 的特殊字符需用 quote 进行 urlencode 编码
    r.uri = "/a/v1/v2/v3/v4"
    r.query = {
        'qv9': 'v9',
        'qv10': 'v10',
        'qv11': 'v11',
        'qv12': 'v12',
        'miracle': 'qijian',
        'str': '1 order by 1',
        'json': '{"remote_addr":"1.1.1.1"}',
        'where': '{"version":{"$gt":24811}}'
    }
Exemple #13
0
# coding=utf-8
import requests
from apig_sdk import signer

if __name__ == '__main__':
    sig = signer.Signer()
    sig.Key = "071fe245-9cf6-4d75-822d-c29945a1e06a"
    sig.Secret = "c6e52419-2270-4cb8-8bd4-ae7fdd01dcd5"

    r = signer.HttpRequest("POST", "http://127.0.0.1:8088/test",
                           {'abc': 'abc'}, 'body')
    sig.Sign(r)
    print(r.headers["X-Sdk-Date"])
    print(r.headers["Authorization"])
    resp = requests.request(r.method,
                            r.scheme + "://" + r.host + r.uri,
                            headers=r.headers,
                            data=r.body,
                            verify=False)
    print(resp.status_code, resp.reason)
    print(resp.content)