Flask-最简单的Python http服务框架使用

环境准备

Python + pip + Flask

sudo easy_install pip
sudo pip install flask

代码如下(做了个jieba分词的服务)

# encoding=utf-8
from flask import request
from flask import Flask
import jieba
import jieba.posseg as pseg
import time
import sys
import json

app = Flask(__name__)
reload(sys)
sys.setdefaultencoding('utf8')


@app.route('/jiebaPsegTest', methods=['POST', 'GET'])
def jiebaPsegTest():
    resultObj = {}
    resultList = []
    content = request.args.get('content', '')
    if content.strip() == '':
        resultObj = result('11001', '分词文本不能为空', resultList)
    else:
        seg_list = pseg.cut(content)
        for word, flag in seg_list:
            if flag == 'company':
                resultList.append(word)

        resultObj = result('10001', '分词成功', resultList)
    return json.dumps(resultObj, ensure_ascii=False)


@app.route('/jiebaInit', methods=['POST', 'GET'])
def jiebaInit():
    app.logger.info('---------------------init------------------')
    app.logger.debug("=========start-time" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    file_name = "/Users/FengZhen/Desktop/python/flask/static/Company.txt"
    jieba.load_userdict(file_name)
    app.logger.debug("=========end-time" + time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
    return "jiebaInit done"


@app.route('/jiebaAddWord', methods=['POST', 'GET'])
def jiebaAddWord():
    content = request.args.get('content', '')
    jieba.add_word(content, 2, 'company')
    return "jiebaAddWord done"


@app.route('/jiebaTest', methods=['POST', 'GET'])
def jiebaTest():
    content = request.args.get('content', '')
    seg_list = jieba.cut(content)
    for seg in seg_list:
        print(seg)
    return "deal done result"


# 返回对象
def result(code, msg, data):
    resultDic = {}
    resultDic['code'] = code
    resultDic['msg'] = msg
    resultDic['data'] = data
    return resultDic

if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)

Flask官方文档:http://docs.jinkan.org/docs/flask/quickstart.html#a-minimal-application

猜你喜欢

转载自www.cnblogs.com/EnzoDin/p/10713949.html