當前位置: 首頁>>代碼示例>>Python>>正文


Python request.method方法代碼示例

本文整理匯總了Python中flask.request.method方法的典型用法代碼示例。如果您正苦於以下問題:Python request.method方法的具體用法?Python request.method怎麽用?Python request.method使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask.request的用法示例。


在下文中一共展示了request.method方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: wechat

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def wechat():
    signature = request.args.get("msg_signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")

    crypto = WeChatCrypto(TOKEN, EncodingAESKey, CorpId)
    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        try:
            echo_str = crypto.check_signature(signature, timestamp, nonce, echo_str)
        except InvalidSignatureException:
            abort(403)
        return echo_str
    else:
        try:
            msg = crypto.decrypt_message(request.data, signature, timestamp, nonce)
        except (InvalidSignatureException, InvalidCorpIdException):
            abort(403)
        msg = parse_message(msg)
        if msg.type == "text":
            reply = create_reply(msg.content, msg).render()
        else:
            reply = create_reply("Can not handle this for now", msg).render()
        res = crypto.encrypt_message(reply, nonce, timestamp)
        return res 
開發者ID:wechatpy,項目名稱:wechatpy,代碼行數:27,代碼來源:app.py

示例2: cron_update_remote_manifest

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def cron_update_remote_manifest():
    """更新數據最後更新時間"""
    from everyclass.rpc.http import HttpRpc

    # 獲取安卓客戶端下載鏈接
    android_manifest = HttpRpc.call(method="GET",
                                    url="https://everyclass.cdn.admirable.pro/android/manifest.json",
                                    retry=True)
    android_ver = android_manifest['latestVersions']['mainstream']['versionCode']
    __app.config['ANDROID_CLIENT_URL'] = android_manifest['releases'][android_ver]['url']

    # 更新數據最後更新時間
    _api_server_status = HttpRpc.call(method="GET",
                                      url=__app.config['ENTITY_BASE_URL'] + '/info/service',
                                      retry=True,
                                      headers={'X-Auth-Token': __app.config['ENTITY_TOKEN']})
    __app.config['DATA_LAST_UPDATE_TIME'] = _api_server_status["data"]["data_time"] 
開發者ID:everyclass,項目名稱:everyclass-server,代碼行數:19,代碼來源:__init__.py

示例3: update_content_in_local_cache

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def update_content_in_local_cache(url, content, method='GET'):
    """更新 local_cache 中緩存的資源, 追加content
    在stream模式中使用"""
    if local_cache_enable and method == 'GET' and cache.is_cached(url):
        info_dict = cache.get_info(url)
        resp = cache.get_obj(url)
        resp.set_data(content)

        # 當存儲的資源沒有完整的content時, without_content 被設置為true
        # 此時該緩存不會生效, 隻有當content被添加後, 緩存才會實際生效
        # 在stream模式中, 因為是先接收http頭, 然後再接收內容, 所以會出現隻有頭而沒有內容的情況
        # 此時程序會先將隻有頭部的響應添加到本地緩存, 在內容實際接收完成後再追加內容
        info_dict['without_content'] = False

        if verbose_level >= 4: dbgprint('LocalCache_UpdateCache', url, content[:30], len(content))
        cache.put_obj(
            url,
            resp,
            obj_size=len(content),
            expires=get_expire_from_mime(parse.mime),
            last_modified=info_dict.get('last_modified'),
            info_dict=info_dict,
        ) 
開發者ID:aploium,項目名稱:zmirror,代碼行數:25,代碼來源:zmirror.py

示例4: try_get_cached_response

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def try_get_cached_response(url, client_header=None):
    """
    嘗試從本地緩存中取出響應
    :param url: real url with query string
    :type client_header: dict
    :rtype: Union[Response, None]
    """
    # Only use cache when client use GET
    if local_cache_enable and parse.method == 'GET' and cache.is_cached(url):
        if client_header is not None and 'if-modified-since' in client_header and \
                cache.is_unchanged(url, client_header.get('if-modified-since', None)):
            dbgprint('FileCacheHit-304', url)
            return generate_304_response()
        else:
            cached_info = cache.get_info(url)
            if cached_info.get('without_content', True):
                # 關於 without_content 的解釋, 請看update_content_in_local_cache()函數
                return None
            # dbgprint('FileCacheHit-200')
            resp = cache.get_obj(url)
            assert isinstance(resp, Response)
            parse.set_extra_resp_header('x-zmirror-cache', 'FileHit')
            return resp
    else:
        return None 
開發者ID:aploium,項目名稱:zmirror,代碼行數:27,代碼來源:zmirror.py

示例5: request_remote_site

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def request_remote_site():
    """
    請求遠程服務器(high-level), 並在返回404/500時進行 domain_guess 嘗試
    """

    # 請求被鏡像的網站
    # 注意: 在zmirror內部不會處理重定向, 重定向響應會原樣返回給瀏覽器
    parse.remote_response = send_request(
        parse.remote_url,
        method=request.method,
        headers=parse.client_header,
        data=parse.request_data_encoded,
    )

    if parse.remote_response.url != parse.remote_url:
        warnprint("requests's remote url", parse.remote_response.url,
                  'does no equals our rewrited url', parse.remote_url)

    if 400 <= parse.remote_response.status_code <= 599:
        # 猜測url所對應的正確域名
        dbgprint("Domain guessing for", request.url)
        result = guess_correct_domain()
        if result is not None:
            parse.remote_response = result 
開發者ID:aploium,項目名稱:zmirror,代碼行數:26,代碼來源:zmirror.py

示例6: check_token

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def check_token(self, token, allowed_roles, resource, method):
        """
        This function is called when a token is sent throught the access_token
        parameter or the Authorization header as specified in the oAuth 2 specification.

        The provided token is validated with the JWT_SECRET defined in the Eve configuration.
        The token issuer (iss claim) must be the one specified by JWT_ISSUER and the audience
        (aud claim) must be one of the value(s) defined by the either the "audiences" resource
        parameter or the global JWT_AUDIENCES configuration.

        If JWT_ROLES_CLAIM is defined and a claim by that name is present in the token, roles
        are checked using this claim.

        If a JWT_SCOPE_CLAIM is defined and a claim by that name is present in the token, the
        claim value is check, and if "viewer" is present, only GET and HEAD methods will be
        allowed. The scope name is then added to the list of roles with the scope: prefix.

        If the validation succeed, the claims are stored and accessible thru the
        get_authen_claims() method.
        """
        resource_conf = config.DOMAIN[resource]
        audiences = resource_conf.get('audiences', config.JWT_AUDIENCES)
        return self._perform_verification(token, audiences, allowed_roles) 
開發者ID:rs,項目名稱:eve-auth-jwt,代碼行數:25,代碼來源:auth.py

示例7: requires_token

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def requires_token(self, audiences=None, allowed_roles=None):
        """
        Decorator for functions that will be protected with token authentication.

        Token must be provvided either through access_token parameter or Authorization
        header.

        See check_token() method for further details.
        """
        def requires_token_wrapper(f):
            @wraps(f)
            def decorated(*args, **kwargs):
                try:
                    token = request.args['access_token']
                except KeyError:
                    token = request.headers.get('Authorization', '').partition(' ')[2]

                if not self._perform_verification(token, audiences, allowed_roles):
                    abort(401)

                return f(*args, **kwargs)
            return decorated
        return requires_token_wrapper 
開發者ID:rs,項目名稱:eve-auth-jwt,代碼行數:25,代碼來源:auth.py

示例8: _perform_verification

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def _perform_verification(self, token, audiences, allowed_roles):
        verified, payload, account_id, roles = verify_token(
                token, self.secret, self.issuer, request.method, audiences, allowed_roles)
        if not verified:
            return False

        # Save roles for later access
        self.set_authen_roles(roles)

        # Save claims for later access
        self.set_authen_claims(payload)

        # Limit access to the authen account
        self.set_request_auth_value(account_id)

        return True 
開發者ID:rs,項目名稱:eve-auth-jwt,代碼行數:18,代碼來源:auth.py

示例9: v1CheckPassword

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def v1CheckPassword():
    username = ''
    password = ''
    if request.method == 'GET':
        username = request.args.get('u','')
        password = request.args.get('p','')
        reserve = True
    elif request.method == 'POST':
        username = request.form.get('u','')
        password = request.form.get('p','')
        reserve = False
    (isGood,code,reason) = pwn.verifyPasswordGood(username,
                                              password,
                                              reserve=reserve,
                                              always_true=cfg.yesman)
    logStore.code = code
    logStore.isValid = isGood
    logStore.user = username

    message = u','.join(map(str,[isGood,code,reason]))
    return message 
開發者ID:CboeSecurity,項目名稱:password_pwncheck,代碼行數:23,代碼來源:password-pwncheck.py

示例10: __init__

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def __init__(cls, name, bases, d):
        # Prepare
        methods = set(cls.methods or [])
        methods_map = defaultdict(dict)
        # Methods
        for view_name, func in inspect.getmembers(cls):
            # Collect methods decorated with methodview()
            info = _MethodViewInfo.get_info(func)
            if info is not None:
                # @methodview-decorated view
                for method in info.methods:
                    methods_map[method][view_name] = info
                    methods.add(method)

        # Finish
        cls.methods = tuple(sorted(methods_map.keys()))  # ('GET', ... )
        cls.methods_map = dict(methods_map)  # { 'GET': {'get': _MethodViewInfo } }
        super(MethodViewType, cls).__init__(name, bases, d) 
開發者ID:kolypto,項目名稱:py-flask-jsontools,代碼行數:20,代碼來源:views.py

示例11: _match_view

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def _match_view(self, method, route_params):
        """ Detect a view matching the query

        :param method: HTTP method
        :param route_params: Route parameters dict
        :return: Method
        :rtype: Callable|None
        """
        method = method.upper()
        route_params = frozenset(k for k, v in route_params.items() if v is not None)

        for view_name, info in self.methods_map[method].items():
            if info.matches(method, route_params):
                return getattr(self, view_name)
        else:
            return None 
開發者ID:kolypto,項目名稱:py-flask-jsontools,代碼行數:18,代碼來源:views.py

示例12: json_classify

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def json_classify():
    if request.method == 'POST':
        img = Image.open(request.files['file'])
        #Format image to Numpy CHW and run inference, get the results of the single output node
        results = engine.infer(image_to_np_CHW(img))[0]
        #Retrive the results created by the post processor callback
        top_class_label, top5 = results[0], results[1]

        #Format data for JSON
        top5_str = []
        for t in top5:
            top5_str.append((t[0], str(t[1])))
        classification_data = {"top_class": top_class_label, "top5": top5_str}

        return jsonify (
            data = classification_data
        )

    else:
        return jsonify (
            error = "Invalid Request Type"
        ) 
開發者ID:aimuch,項目名稱:iAI,代碼行數:24,代碼來源:resnet_as_a_service.py

示例13: json_classify

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def json_classify():
    if request.method == 'POST':
        img = Image.open(request.files['file'])        
        #Format image to Numpy CHW and run inference, get the results of the single output node
        results = engine.infer(image_to_np_CHW(img))[0]
        #Retrive the results created by the post processor callback
        top_class_label, top5 = results[0], results[1]

        #Format data for JSON
        top5_str = []
        for t in top5:
            top5_str.append((t[0], str(t[1])))
        classification_data = {"top_class": top_class_label, "top5": top5_str}

        return jsonify (
            data = classification_data
        )

    else:
        return jsonify (
            error = "Invalid Request Type"
        ) 
開發者ID:aimuch,項目名稱:iAI,代碼行數:24,代碼來源:resnet_as_a_service.py

示例14: cryptolist

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def cryptolist():
    getlist = listofcrypto.query.all()

    if request.method == "GET":
        check = request.args.get("json")
        q = request.args.get("term")
        if check == "true":
            jsonlist = []
            for item in getlist:
                if (q.upper() in item.symbol) or (q in item.name):
                    tmp = {}
                    tmp["name"] = item.name
                    tmp["symbol"] = item.symbol
                    jsonlist.append(tmp)

            return jsonify(jsonlist)

    return render_template(
        "cryptolist.html",
        title="List of Crypto Currencies", listofcrypto=getlist
    ) 
開發者ID:pxsocs,項目名稱:thewarden,代碼行數:23,代碼來源:routes.py

示例15: aclst

# 需要導入模塊: from flask import request [as 別名]
# 或者: from flask.request import method [as 別名]
def aclst():
    list = []
    if request.method == "GET":

        tradeaccounts = Trades.query.filter_by(
            user_id=current_user.username).group_by(
            Trades.trade_account)

        accounts = AccountInfo.query.filter_by(
            user_id=current_user.username).group_by(
            AccountInfo.account_longname
        )

        q = request.args.get("term")
        for item in tradeaccounts:
            if q.upper() in item.trade_account.upper():
                list.append(item.trade_account)
        for item in accounts:
            if q.upper() in item.account_longname.upper():
                list.append(item.account_longname)

        list = json.dumps(list)

        return list 
開發者ID:pxsocs,項目名稱:thewarden,代碼行數:26,代碼來源:routes.py


注:本文中的flask.request.method方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。