Python flask.request.method() Examples

The following are 30 code examples of flask.request.method(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.request , or try the search function .
Example #1
Source Project: beavy   Author: beavyHQ   File: views.py    License: Mozilla Public License 2.0 9 votes vote down vote up
def submit_story():
    if request.method == "POST":
        params = request.get_json()
        title, url = params['title'].strip(), params['url'].strip()
        text = params.get('text', "").strip()
        if not title:
            return abort(400, "You have to provide a 'title'")

        if url:
            link = Link(title=title, url=url, owner_id=current_user.id)
            db.session.add(link)
            db.session.commit()
            return link_schema.dump(link)
        elif text:
            topic = Topic(title=title, text=text, owner_id=current_user.id)
            db.session.add(topic)
            db.session.commit()
            return topic_schema.dump(topic)

        return abort(400, "You have to provide either 'url' or 'text', too")

    # Just render it
    return {} 
Example #2
Source Project: wechatpy   Author: wechatpy   File: app.py    License: MIT License 7 votes vote down vote up
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 
Example #3
Source Project: everyclass-server   Author: everyclass   File: __init__.py    License: Mozilla Public License 2.0 6 votes vote down vote up
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"] 
Example #4
Source Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 votes vote down vote up
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,
        ) 
Example #5
Source Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 votes vote down vote up
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 
Example #6
Source Project: zmirror   Author: aploium   File: zmirror.py    License: MIT License 6 votes vote down vote up
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 
Example #7
Source Project: eve-auth-jwt   Author: rs   File: auth.py    License: MIT License 6 votes vote down vote up
def authorized(self, allowed_roles, resource, method):
        authorized = False

        if request.authorization:
            auth = request.authorization
            authorized = self.check_auth(auth.username, auth.password,
                                         allowed_roles, resource, method)
        else:
            try:
                access_token = request.args['access_token']
            except KeyError:
                access_token = request.headers.get('Authorization', '').partition(' ')[2]
            authorized = self.check_token(access_token, allowed_roles, resource, method)

        return authorized 
Example #8
Source Project: eve-auth-jwt   Author: rs   File: auth.py    License: MIT License 6 votes vote down vote up
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) 
Example #9
Source Project: eve-auth-jwt   Author: rs   File: auth.py    License: MIT License 6 votes vote down vote up
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 
Example #10
Source Project: eve-auth-jwt   Author: rs   File: auth.py    License: MIT License 6 votes vote down vote up
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 
Example #11
Source Project: password_pwncheck   Author: CboeSecurity   File: password-pwncheck.py    License: MIT License 6 votes vote down vote up
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 
Example #12
Source Project: py-flask-jsontools   Author: kolypto   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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) 
Example #13
Source Project: py-flask-jsontools   Author: kolypto   File: views.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #14
Source Project: iAI   Author: aimuch   File: resnet_as_a_service.py    License: MIT License 6 votes vote down vote up
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"
        ) 
Example #15
Source Project: iAI   Author: aimuch   File: resnet_as_a_service.py    License: MIT License 6 votes vote down vote up
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"
        ) 
Example #16
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
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
    ) 
Example #17
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
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 
Example #18
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
def tradedetails():
    if request.method == "GET":
        id = request.args.get("id")
        # if tradesonly is true then only look for buy and sells
        tradesonly = request.args.get("trades")
        df = pd.read_sql_table("trades", db.engine)
        # Filter only the trades for current user
        df = df[(df.user_id == current_user.username)]
        df = df[(df.trade_reference_id == id)]
        # Filter only buy and sells, ignore deposit / withdraw
        if tradesonly:
            df = df[(df.trade_operation == "B") | (df.trade_operation == "S")]
        # df['trade_date'] = pd.to_datetime(df['trade_date'])
        df.set_index("trade_reference_id", inplace=True)
        df.drop("user_id", axis=1, inplace=True)
        details = df.to_json()
        return details 
Example #19
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
def login():
    if current_user.is_authenticated:
        return redirect(url_for("main.home"))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            # The get method below is actually very helpful
            # it returns None if empty. Better than using [] for a dictionary.
            next_page = request.args.get("next")  # get the original page
            if next_page:
                return redirect(next_page)
            else:
                return redirect(url_for("main.home"))
        else:
            flash("Login failed. Please check e-mail and password", "danger")

    return render_template("login.html", title="Login", form=form) 
Example #20
Source Project: thewarden   Author: pxsocs   File: routes.py    License: MIT License 6 votes vote down vote up
def account():
    form = UpdateAccountForm()
    if form.validate_on_submit():
        # Recalculate the NAV
        current_user.image_file = form.basefx.data
        current_user.email = form.email.data
        db.session.commit()
        regenerate_nav()
        flash(
            f"Account updated and NAV recalculated to use " +
            f"{form.basefx.data} as a base currency", "success")
        return redirect(url_for("users.account"))

    elif request.method == "GET":
        form.email.data = current_user.email
        # Check if the current value is in list of fx
        # If not, default to USD
        fx = fx_list()
        found = [item for item in fx if current_user.image_file in item]
        if found != []:
            form.basefx.data = current_user.image_file
        else:
            form.basefx.data = "USD"

    return render_template("account.html", title="Account", form=form) 
Example #21
Source Project: app   Author: simple-login   File: unsubscribe.py    License: MIT License 6 votes vote down vote up
def unsubscribe(alias_id):
    alias = Alias.get(alias_id)
    if not alias:
        flash("Incorrect link. Redirect you to the home page", "warning")
        return redirect(url_for("dashboard.index"))

    if alias.user_id != current_user.id:
        flash(
            "You don't have access to this page. Redirect you to the home page",
            "warning",
        )
        return redirect(url_for("dashboard.index"))

    # automatic unsubscribe, according to https://tools.ietf.org/html/rfc8058
    if request.method == "POST":
        alias.enabled = False
        flash(f"Alias {alias.email} has been blocked", "success")
        db.session.commit()

        return redirect(url_for("dashboard.index", highlight_alias_id=alias.id))
    else:  # ask user confirmation
        return render_template("dashboard/unsubscribe.html", alias=alias.email) 
Example #22
Source Project: app   Author: simple-login   File: recovery_code.py    License: MIT License 6 votes vote down vote up
def recovery_code_route():
    if not current_user.two_factor_authentication_enabled():
        flash("you need to enable either TOTP or WebAuthn", "warning")
        return redirect(url_for("dashboard.index"))

    recovery_codes = RecoveryCode.query.filter_by(user_id=current_user.id).all()
    if request.method == "GET" and not recovery_codes:
        # user arrives at this page for the first time
        LOG.d("%s has no recovery keys, generate", current_user)
        RecoveryCode.generate(current_user)
        recovery_codes = RecoveryCode.query.filter_by(user_id=current_user.id).all()

    if request.method == "POST":
        RecoveryCode.generate(current_user)
        flash("New recovery codes generated", "success")
        return redirect(url_for("dashboard.recovery_code_route"))

    return render_template(
        "dashboard/recovery_code.html", recovery_codes=recovery_codes
    ) 
Example #23
Source Project: dota2-predictor   Author: andreiapostoae   File: app.py    License: MIT License 6 votes vote down vote up
def home():
    if request.method == "POST":
        #do back end things here and then return what we want, take it back in a success function in JS and update the page.
        heroes = [name.encode('UTF8') for name in request.json['heroes']]
        radiant = [get_hero_id(hero) for hero in heroes[:5] if get_hero_id(hero)]
        dire = [get_hero_id(hero) for hero in heroes[5:] if get_hero_id(hero)]
        mmr = int(request.json['mmr'])

        text = query(mmr, radiant, dire)

        if isinstance(text, list):
            text = ''.join([str(hero[0]) + ': ' + str(round(hero[1][0] * 100, 2))+'% win rate. <br>' for hero in text[:10]])

        return text

    hero_names = get_full_hero_list()
    radiant_heroes, dire_heroes = get_hero_factions()
    edited_names = [name.replace(" ", "_").replace("\'", "").lower() for name in hero_names]
    return render_template('main2.html', hero_names=sorted(hero_names), edited_names=sorted(edited_names), radiant_heroes=radiant_heroes, dire_heroes=dire_heroes) 
Example #24
Source Project: xcessiv   Author: reiinakano   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def extraction_main_dataset():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.main_dataset)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.main_dataset[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.main_dataset) 
Example #25
Source Project: xcessiv   Author: reiinakano   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def extraction_test_dataset():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.test_dataset)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.test_dataset[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.test_dataset) 
Example #26
Source Project: xcessiv   Author: reiinakano   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def extraction_meta_feature_generation():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.meta_feature_generation)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.meta_feature_generation[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.meta_feature_generation) 
Example #27
Source Project: xcessiv   Author: reiinakano   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def extraction_stacked_ensemble_cv():
    path = functions.get_path_from_query_string(request)

    if request.method == 'GET':
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            return jsonify(extraction.stacked_ensemble_cv)

    if request.method == 'PATCH':
        req_body = request.get_json()
        with functions.DBContextManager(path) as session:
            extraction = session.query(models.Extraction).first()
            for key, value in six.iteritems(req_body):
                extraction.stacked_ensemble_cv[key] = value
            session.add(extraction)
            session.commit()
            return jsonify(extraction.stacked_ensemble_cv) 
Example #28
Source Project: xcessiv   Author: reiinakano   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def specific_base_learner(id):
    path = functions.get_path_from_query_string(request)

    with functions.DBContextManager(path) as session:
        base_learner = session.query(models.BaseLearner).filter_by(id=id).first()
        if base_learner is None:
            raise exceptions.UserError('Base learner {} not found'.format(id), 404)

        if request.method == 'GET':
            return jsonify(base_learner.serialize)

        if request.method == 'DELETE':
            base_learner.cleanup(path)
            session.delete(base_learner)
            session.commit()
            return jsonify(message='Deleted base learner') 
Example #29
Source Project: telegram-innovation-chatbot   Author: zaoldyeck   File: main.py    License: MIT License 5 votes vote down vote up
def webhook_handler():
    """Set route /hook with POST method will trigger this method."""
    if request.method == "POST":
        update = telegram.Update.de_json(request.get_json(force=True), bot)
        dispatcher.process_update(update)
    return 'ok' 
Example #30
Source Project: wechatpy   Author: wechatpy   File: app.py    License: MIT License 5 votes vote down vote up
def wechat():
    signature = request.args.get("signature", "")
    timestamp = request.args.get("timestamp", "")
    nonce = request.args.get("nonce", "")
    encrypt_type = request.args.get("encrypt_type", "raw")
    msg_signature = request.args.get("msg_signature", "")
    try:
        check_signature(TOKEN, signature, timestamp, nonce)
    except InvalidSignatureException:
        abort(403)
    if request.method == "GET":
        echo_str = request.args.get("echostr", "")
        return echo_str

    # POST request
    if encrypt_type == "raw":
        # plaintext mode
        msg = parse_message(request.data)
        if msg.type == "text":
            reply = create_reply(msg.content, msg)
        else:
            reply = create_reply("Sorry, can not handle this for now", msg)
        return reply.render()
    else:
        # encryption mode
        from wechatpy.crypto import WeChatCrypto

        crypto = WeChatCrypto(TOKEN, AES_KEY, APPID)
        try:
            msg = crypto.decrypt_message(request.data, msg_signature, timestamp, nonce)
        except (InvalidSignatureException, InvalidAppIdException):
            abort(403)
        else:
            msg = parse_message(msg)
            if msg.type == "text":
                reply = create_reply(msg.content, msg)
            else:
                reply = create_reply("Sorry, can not handle this for now", msg)
            return crypto.encrypt_message(reply.render(), nonce, timestamp)