Flask服务入门案例

安装

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

 

posted @ 2016-01-06 00:29  jihite  阅读(1789)  评论(0编辑  收藏  举报