这一课看完后, 又跑去一些视频网站看了许多视频, 油管上一位播主Yufan Zheng讲解Flask中涉及到了书的许多知识点, 让我比较好的理解了它们.
下面是app.py代码
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route("/hello", methods=['POST','GET'])
def index():
greeting = 'Hello World'
if request.method == 'POST':
name = request.form['name']
greet = request.form['greet']
print('走的if', request.method) #为了方便查看走的哪一条线路
greeting = f"{greet}, {name}"
return render_template("index.html", greeting=greeting)
else:
print('走的else', request.method) #为了方便查看走的哪一条线路
return render_template("hello_form.html")
if __name__ == "__main__":
app.run()
上面打印了两条线路,可以方便的查看是post 还是 get
下面是app_tests.py
from nose.tools import *
from app import app
app.config['TESTING'] = True # 不明白
web = app.test_client() #不明白
def test_index():
rv = web.get('/', follow_redirects=True) #类似requests.get('https://xxx.xxx.xxx')
assert_equal(rv.status_code, 404) #比较返回的状态码, 正常访问应该是200,错误会是404)
rv = web.get('/hello', follow_redirects=True) #rv接受到回传
assert_equal(rv.status_code, 200)
assert_in(b'Fill Out This Form', rv.data) #查看rv.data里面是否有fill out 䚱是bytes
data ={'name' : 'Zed', 'greet' : 'Hola'}
rv =web.post('/hello', follow_redirects=True, data=data) #post方式,把name greet传上去并拿到回传
assert_in(b"Zed", rv.data) #查看rv.data里面是否有Zed 䚱是bytes
assert_in(b"Hola", rv.data)#查看rv.data里面是否有Hola 䚱是bytes
上面有几多代码书中都没有解释,给小白我学习带来了麻烦, 百度后也没结果 ,先放着一边, 把能理解的先消化.
下面是nosetests 测试结果 ,测试时发现由于app_tests.py里面有一句 from app impor app, 这是要从app.py里面import app对象,从Flask()生成的实例, 但是这样引用又必须要有__init__.py, 问题来了nosetests与Python3.8兼容有问题,必须 删除被 测试文件同文件夹里面的__init__.py 还有 tests文件夹里面的__init__.py , 可是删除后, from app import app就无法找到app.py了, 要么重装Python3.6与书Zed同时期python版本相符, 要么把app.py 从 gothonweb 文件夹里面移到出来 , 于是我自然选择了第二个试, 成功测试代码成功, 如果 有谁知道更好的方法欢迎提供,目前就以这个方法测试.
下面是index.html代码, 其中为了方便在网页识别继承的是谁的信息, 特地写了from xxxxxxx来自哪的html
{% extends 'layout.html' %}
{% block content %}
{% if greeting %}
I just wanted to say
<em style="color: green; font-size: 2em"> {{ greeting }} </em> from index.html
{% else %}
<em>Hello</em>World
{% endif %}
<br>
<a href="/hello">跳到hello_form.html去</a>
{% endblock %}
下面是hello_form.html代码
{% extends 'layout.html' %}
{% block content %}
<h1>Fill Out This Form from hello_form.html</h1>
<form action="/hello" method="POST">
A Greet from hello_form post <input type="text" name="greet">
<br>
Your Name from hello_form post <input type="text" name="name">
<br>
<input type="submit">
</form>
{% endblock %}
下面是layout.html, 这种方式比较像外套一样, 如果你写的网页头部尾部不怎么变化,那么可以写一个xxx.html, 别的html来继承 extends或者引用include
<html>
<head>
<title>Gothons From Planet percal #25 From layou.html</title>
</head>
<body>
{% block content %}
{% endblock %}
</body>
</html>