简体   繁体   English

Elif 条件未执行

[英]Elif condition not executed

So I'm trying to do some json request with Postman.所以我试图用 Postman 做一些 json 请求。 This is my code:这是我的代码:

def create_app():
    app = Flask(__name__)

    @app.route('/', methods=['POST'])
    def index():
        news_site = request.get_json()
        print(news_site)
        if news_site.get('kompas', True) & news_site.get('detik', True) == True:
            scrapdata = kompas_fun(), detik_fun()
            return jsonify(scrapdata)
        elif news_site.get('kompas', True) & news_site.get('detik', False) == True:
            scrapdata = kompas_fun()
            return jsonify(scrapdata)
        elif news_site.get('kompas', False) & news_site.get('detik', True) == True:
            scrapdata = detik_fun()
            return jsonify(scrapdata)
        else:
            return jsonify({'value': 'error'})
    return app

The if condition works, but don't know why that two elif conditions ignored then just go directly to else when the input is kompas=True, detik=False , or kompas=False, detik=True . if条件有效,但不知道为什么忽略了两个elif条件,然后当输入为kompas=True, detik=Falsekompas=False, detik=True时,直接将 go 直接转换为else I already tried without == True , replacing & with and but still same.我已经尝试不使用== True ,将&替换为and但仍然相同。 And here is the result of news_site print and terminal output:这是news_site打印和终端 output 的结果:

(env) PS D:\demotest> flask run
 * Serving Flask app "run.py" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 318-319-173
 * Running on http://127.0.0.1:8080/ (Press CTRL+C to quit)
{'kompas': False, 'detik': True}
127.0.0.1 - - [26/Nov/2020 20:05:48] "POST / HTTP/1.1" 200 -
{'kompas': True, 'detik': False}
127.0.0.1 - - [26/Nov/2020 20:06:03] "POST / HTTP/1.1" 200 -
{'kompas': True, 'detik': True}

The first and second input resulting else output.第一个和第二个输入结果else But the third one executed perfectly.但是第三个执行得很完美。 I dont understand why.我不明白为什么。 Any help would be appreciated.任何帮助,将不胜感激。

& is a binary operator, not a logical operator. &是二元运算符,而不是逻辑运算符。 Are you maybe looking for您是否正在寻找

@app.route("/", methods=["POST"])
def index():
    news_site = request.get_json()
    kompas = bool(news_site.get("kompas"))
    detik = bool(news_site.get("detik"))
    scrapdata = []
    if kompas:
        scrapdata.append(kompas_fun())
    if detik:
        scrapdata.append(detik_fun())
    return jsonify(scrapdata)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM