Flask框架快如入门
1.Flask框架简介
Flask是一个微型的Python开发的Web框架,可以用于快速实现一个网站或Web服务。基于Werkzeug WSGI工具箱和jinja2模板引擎,官方参考文档:https://flask.palletsprojects.com/en/2.0.x/ Flask与Django都是后端框架,只是前者属于微框架,后者属于重量级框架。框架的核心就是实现路由和视图函数
2.Flask快速入门
2.1 安装Flask
在anaconda安装的环境下执行安装命令即可
pip install flask
2.2 快速入门
from flask import Flask #1.导入flask库文件
app = Flask(__name__)
"""flask初始化 ,创建程序实例,flask类只有一个必须指定的参数,程序主模块或者包的名字,__name__是系统变量"""
@app.route("/") #2.路由和视图函数 处理url和pythonC函数之间的关系程序称作路由
def hi_welcome(): #url路径下对应的代码为hi_welcom() 当执行url会执行相应代码
return "Hi Welcome"
if __name__ == "__main__": #3.程序实例调用run方法,启动flask集成的开发web服务器
app.run()
- 客户端发送url给web服务器,web服务器将url转发给flask程序实例;每个url请求启动一部分代码,因此保存了url和python函数的映射关系,处理url和函数之间关系的程序称作路由。
- 上述代码的具体流程为:
(1)浏览器将请求给web服务器,web服务器将请求给app
(2)app收到请求,通过路由找到对应的视图函数,然后请求处理,得到一个相应response
(3)然后app将响应返回给web服务器
(4)web服务器返回给浏览器
(5)浏览器展示给用户观看
2.3 前端、后端、客户端、服务器的相关概念
- 前端指的是通过浏览器与用户交互的那部分
- 后端是在服务器上执行的部分,一般是管理数据,为前端和客户端提供数据传输的
- 客户端就是值开发面向客户的程序,属于前端
- 服务器就是后端
3.项目实战
#Chengjinpei
from flask import Flask,render_template,request
#系统
import os
import tensorflow as tf
import pickle
#自定义
import data_utils
import model_utils
from model import Model
#创建flask实例
app = Flask(__name__)
flags = tf.app.flags
#配置相关
flags.DEFINE_string('ckpt_path', os.path.join('modelfile', 'ckpt'), '保存模型的位置')
flags.DEFINE_string('map_file', 'maps.pkl', '存放字典映射及标签映射')
flags.DEFINE_string('config_file', 'config_file', '配置文件')
FLAGS = tf.app.flags.FLAGS
config = model_utils.load_config(FLAGS.config_file)
tf_config = tf.ConfigProto()
tf_config.gpu_options.allow_growth = True
with open(FLAGS.map_file, "rb") as f:
word_to_id, id_to_word, tag_to_id, id_to_tag = pickle.load(f)
def evaluate_line(line):
with tf.Session(config = tf_config) as sess:
model = model_utils.create(sess, Model, FLAGS.ckpt_path, config) #调用已经训练好的模型
result = model.evaluate_line(sess, data_utils.input_from_line(line, word_to_id), id_to_tag) #测试训练好的模型
return result
#路由
@app.route('/')
def index():
return render_template("index.html") #主页html界面
@app.route('/getNER',methods=['POST'])
def getNER():
source = request.form.get('source') # 命名实体视图函数
result = evaluate_line(source)
return result
@app.route('/getPer',methods=['POST'])
def getPer():
source = request.form.get('per') #获取人名实体视图函数
result = evaluate_line(source)
#print(type(result))
if result is None:
return "没有可识别的实体"
entites = result['entities']
per = []
for entity in entites:
if entity['type'] == "PER":
per.append(entity['word'])
return " ".join(per)
@app.route('/getOrg',methods=['POST'])#获取机构实体视图函数
def getOrg():
source = request.form.get('org')
result = evaluate_line(source)
#print(type(result))
if result is None:
return "没有可识别的实体"
entites = result['entities']
org = []
for entity in entites:
if entity['type'] == "ORG":
org.append(entity['word'])
return " ".join(org)
if __name__ == '__main__':
app.run(debug=True, port='5000', host='127.0.0.1')
#设置调试模式打开,设置访问flask_web应用的端口是5000, 设置访问flask_web应用的ip是127.0.0.1,如果部署到docker中,为了避免出现无法访问的情况,需要将host设置成'0.0.0.0'
详细代码请访问我的github:https://github.com/chengjinpei/BILSTM-CRF_code