Flask服務入門案例

weixin_33896726發表於2016-01-06

安裝

pip install Flask

 

入門例子

from flask import Flask
app = Flask(__name__)

@app.route('/hello.world')
def check():
    return 'hello world!'


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=80)   #指定了費debug模式,外部可訪問的伺服器,埠

請求

$curl http://10.177.80.30:80/hello.world
hello world!

錯誤案例

from flask import Flask

app = Flask(__name__)

@app.route('/hello.world')
def check():
    return 200


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=80)

注:返回值不可為整數

變數規則

from flask import Flask
app = Flask(__name__)

@app.route('/h/<user>')
def check(user):
    return "hello world: %s" % user


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=801)

請求:

$curl http://10.125.8.116:801/h/lalala
hello world: lalala

輸出PUT、POST請求中的引數

from flask import Flask
from flask import request
import os
app = Flask(__name__)

@app.route('/testcase', methods=['GET', 'POST'])
def test():
    if request.method == 'POST':
        msg = request.form.get('msg')
        return 'post msg:', msg
    else:
        msg =  request.args.get('msg')
        return 'put msg:', msg


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0', port=8099)

 

參考:http://docs.jinkan.org/docs/flask/quickstart.html

 

相關文章