flask制作聊天机器人程序
(2022-03-20 07:26:36)分类: 研究-学习 |
Flask是浙教版教材中的一个项目应用案例,可以实现简单的人机对话程序。
#http://127.0.0.1:5000
默认后面有一个/
,即访问的地址为 http://127.0.0.1:5000/
return "hello"
#返回字符串
return
"hello2"
return 'say something to
me'
#return "hello3"
return render_template('hello.html')
#超链接到一个网页(同级目录templates下)
n=request.args.get('name')
#获取字段,name参数值来源于URL地址
return 'hello'+n
return render_template('say.html')
msg=request.form.get('msg')
reply="请重说一遍,我听不懂你说的话。"
if "你好" in msg:
reply="你好啊!"
if '再见' in msg:
reply="再见!"
return
render_template('say.html',reply=reply)
前两天在群里看见了宁波裘成老师发的一个零基础教学视频,讲解的非常详细,便照着学习了起来。(之前也看了浙江瑞清中学的一位老师的教学视频,但觉得很难搞透彻便没有坚持下来。)虽然在跟随裘老师教学视频进行学习的过程中有几个问题在本机没能调试成功,但flask的基本功能和应用应该已经基本搞清楚了。
(1)最基本的代码如下:
#----------------------
from flask import
Flask # flask--库, Flask--类
app=Flask('hello
world') #hello world
类似于标识符,直接作用不是很大。
@app.route('/')
# @是一个装饰器,把这行代码的下一个函数注册到对应的路由中
def index():
#定义一个函数
app.run()
#相当于一个死循环,一直在运行,导致后面的语句都不会执行
print('123')
#这行语句就不会被运行
#-------------------------
(2)绑定了“/h”路由,即访问地址变成了 http://127.0.0.1:5000/h
#-------------------------
from flask import
Flask
app=Flask('hello world')
@app.route('/h')
#http://127.0.0.1:5000/h
此时绑定了/h的路由
def
index():
#----------------
(3)可以加入多个路由(访问不同的路径);在定义函数的返回值里能够识别html语言。如
...
【一号标题】;saysomething等#--------------------------
from flask import
Flask
app=Flask('hello world')
#-----------
@app.route('/say/something') #路由可以是多级的
def say():
#-------------
@app.route('/h')
def index(): #定义一个函数
# return
"hello2"#返回字符串
# return'《h1》hello《/h2》
#2号标题 ———支持html语言
hello2
'# return 'hello2'
#html语言
超链接--返回的不仅仅是一个字符串,浏览器接收后会尝试进行html解析
app.run()
#----------------
#如果返回页面内容很多,都在这里写就显得不方便不合理,可以事先写好一个页面,放在templates
(4)在路由的自定义函数中,返回值是一个网页:
此时网页的位置是在与py文件同级目录的templates文件夹下。同时需要调用flask库的render_template模块。
#------------------------
from flask import
Flask,render_template
app=Flask('hello world')
@app.route('/h')
def index():
#定义一个函数
app.run()
#-----------------------------
#hello.html内容
《html》
《head》
《body》
《h1》hello《/h1》
你好
《/body》
《/html》
hello
你好
#----------
##我在本机测试时就是在此处出现了问题,怎么也调试不出来##
(5)获取动态字段:[get]
[post]等方式传参数,get明文传参,在地址栏中能够看出,如
http://127.0.0.1:5000/h
?name=张三
#------------------
#from flask import
Flask,render_template,request
from flask import Flask,request
app=Flask('hello world')
@app.route('/h')
def index():
app.run()
#------------------------
(6)get传参安全性不够。post方式,需要在网页中用到占位符 {{
参数名 }}
#say.html
内容。内涵reply占位符和一个form表单。表单用于输入对话内容。
《html》
《head》
《meta charset='utf-8'》
《/head》
《body》
《h1》机器人说: {{reply}} 《/h1》
《form action='/h' methods="POST"》
《input name="msg"》
《input type="submit" name="提交"》
《/form》
《/body》
《/html》
机器人说: {{reply}}
#--------------------------------
#py内容:
from flask import
Flask,request,render_template
app=Flask('hello
world')
@app.route('/h')
# @app.route('/h',methods=['get'])
def
hello():
@app.route('/h',methods=['post'])
def
hello_post():
app.run()
#-------------------------------
这里面涉及的过程还比较复杂,有时间时还要慢慢梳理。
前一篇:求最大公约数(两种方法)
后一篇:flask制作聊天机器人程序2