赞
踩
视图函数的返回值会自动转换为一个相应对象;
make_response()用于构建response对象;
在视图函数的返回值可以是:
render_template()与redirect()的区别:
render_template():直接渲染模板,浏览器地址栏中的url不会改变,一次请求响应
redirect():重定向页面,用户发送请求(eg. http://127.0.0.1:5000/news),服务器接收到后返回一个response(eg. 包括head[‘location’]=‘/notfound’ code=302),用户接收到重定向后的信息,再次向服务器发送请求(eg. http://127.0.0.1:5000/notfound),服务器再根据路由返回
from flask import Flask, make_response import settings app = Flask(__name__) app.config.from_object(settings) @app.route('/') def hello_world(): return 'HELLO world!' # 响应对象 @app.route('/abc') def s_abc(): s = '''<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ABC</title> </head> <body> <h1>ABC</h1> </body> </html> ''' response = make_response(s) # 在响应头添加键值对 response.headers['name'] = 'yyf' return response if __name__ == '__main__': app.run()
返回结果如下:
from flask import Flask import settings app = Flask(__name__) app.config.from_object(settings) @app.route('/') def hello_world(): return 'HELLO hello hello hello world!' @app.route('/abc') def s_abc(): dict = {'name': 'yyf', 'age': 20} return dict if __name__ == '__main__': app.run()
返回结果:
from flask import Flask, jsonify import settings app = Flask(__name__) app.config.from_object(settings) @app.route('/') def hello_world(): return 'HELLO hello hello hello world!' @app.route('/abc') def s_abc(): list = ['a', 'v', 's', 'e', 'q'] return jsonify(list) if __name__ == '__main__': app.run()
返回结果:
from flask import Flask, render_template
import settings
app = Flask(__name__) # template_folder: t.Optional[str] = "templates", 模板默认文件夹为templates
app.config.from_object(settings)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
返回结果:
from flask import Flask, render_template, request import settings app = Flask(__name__) # template_folder: t.Optional[str] = "templates", 模板默认文件夹为templates app.config.from_object(settings) @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': pass return render_template('login.html') if __name__ == '__main__': app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
<a href="/login">登录</a>
<a href="">注册</a>
<hr>
<a href="">新闻</a>
<a href="">体育</a>
<a href="">热点</a>
</body>
</html>
当点击登录按钮,页面跳转到’/login’页面上
from flask import Flask, render_template, redirect import settings app = Flask(__name__) app.config.from_object(settings) @app.route('/') def index(): return render_template('index.html') news = [] @app.route('/news') def show_news(): if not news: return redirect('/notfound') # URL:http://127.0.0.1:5000/notfound # return render_template('404.html') # URL:http://127.0.0.1:5000/news @app.route('/notfound') def not_found(): return render_template('404.html') if __name__ == '__main__': app.run()
当点击新闻时,用户与浏览器发生两次请求响应,如下图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。