完成本章学习后,你将能够:
from flask import Flask, jsonify, request, render_template app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' @app.route('/user/<name>') def user(name): return f'Hello, {name}!' @app.route('/api/data', methods=['GET', 'POST']) def data(): if request.method == 'POST': data = request.json return jsonify({'received': data}), 201 return jsonify({'message': 'GET request'}) if __name__ == '__main__': app.run(debug=True)
from flask import render_template @app.route('/hello/<name>') def hello_template(name): return render_template('hello.html', name=name)
<!-- templates/hello.html -->
<!DOCTYPE html>
<html>
<head><title>Hello</title></head>
<body>
<h1>Hello, {{ name }}!</h1>
{% if name == 'admin' %}
<p>Welcome, administrator!</p>
{% endif %}
</body>
</html>