template 与视图关联

import json

from flask import Flask, request, make_response, render_template, url_for

import settings

users = []
app = Flask(__name__)
app.config.from_object(settings)

@app.route('/index')
def index():
print(request.headers)
print(request.path)
print(request.url)
return 'welcome everyone'


@app.route('/register3')
def register():
r = render_template('register.html')
print(r)
return r


@app.route('/register2')
def register2():
#return '进来了'
print(request.full_path)
print(request.path)
print(request.args)
print(request.args.get('username'))
print(request.args.get('address'))


###如果通过POST方式的话,在route 中 传递参数 method=['POST']
###通过request.form.get('username') request.form.get('adddress')
'''
POST方式时,会将信息隐藏于请求体FormData中,而GET会显示在URL中,因此一般都使用POST方式
POST方式时,必须要有返回值。
'''



@app.route('/register',methods=['GET','POST'])
def register11():
print(request.method)
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
repassword=request.form.get('repassword')
if password == repassword:
user={'username':username,'password':password}
users.append(user)
#return '注册成功!'
return redirect('/') ##重定向 返回一个新的地址,并且返回状态码302,浏览器接收到新地址和302后,会根据新的地址重新请求
else:
return '两次密码不一致'

return render_template('register.html',result) ##通过render 将html页面转换为response类型并返回




@app.route('/show')
def show():
'''将列表类型数据转换为Json文件返回'''
j_str = json.dumps(users)
return j_str


@app.route('/test',endpoint='xiaoming') ###将路由设置一个别名,便于记忆,通过url_for来反向解析成路由
def test():
url=url_for('xiaoming')
print(url)
return 'test'

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



#############
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎来到京东购物网站</title>
</head>
<h1>欢迎哈</h1>
<url>
<li>Hello abc</li>
<li>Hi 123</li>
<li>World</li>>
</url>


<!--如果是表单提交,必须加name属性-->
<form action="register" method="POST">
<p><input type="text" name='username' placeholder="请输入用户名"></p>
<p><input type="text" name='address' placeholder="请输入地址"></p>
<p><input type="submit" value="提交"></p>
<p>结果{{result}}</p>
</form>>



<body>

</body>
</html>
posted @ 2021-07-12 21:24  oceaning  阅读(47)  评论(0编辑  收藏  举报