responses
+65 −11 · 3 files changed
-
flask-blog.py+41 −1 -
templates/index.html+22 −10 -
templates/text.txt+2 −0
@@ -1,7 +1,8 @@ import os import imghdr from datetime import datetime -from flask import Flask, render_template, request, session, g +from flask import Flask, render_template, request, session, g, \ + make_response, jsonify, url_for, redirect from flask.ext.bootstrap import Bootstrap from flask.ext.wtf import Form from wtforms import StringField, SubmitField, FileField, ValidationError @@ -35,6 +36,45 @@ def hello_world(): return render_template('index.html') +@app.route('/text') +def text(): + return render_template('text.txt'), 200, {'Content-Type': 'text/plain'} + + +@app.route('/xml') +def xml(): + return '<h1>this is shown as <b>XML</b> in the browser</h1>', 200, \ + {'Content-Type': 'application/xml'} + + +@app.route('/json') +def json(): + return jsonify({'first_name': 'john', 'last_name': 'Smith'}) + + +@app.route('/redirect') +def redir(): + return redirect(url_for('text')) + + +@app.route('/cookie') +def cookie(): + resp = redirect(url_for('index')) + resp.set_cookie('cookie', 'Hello, im a cookie') + return resp + + +@app.route('/error') +def error(): + return 'Bad Request', 400 + + +@app.route('/response') +def response(): + resp = make_response(render_template('text.txt')) + resp.headers['Content-Type'] = 'text/plain' + return resp + @app.route('/user/<name>') def user(name): return render_template('user.html', name=name) @@ -1,10 +1,22 @@ -<!DOCTYPE html> -<html> -<head lang="en"> - <meta charset="UTF-8"> - <title></title> -</head> -<body> - <h1>Hello World</h1> -</body> -</html> \ No newline at end of file +<h1>This page containes HTML</h1> +<p> + Cookie: + {% if 'cookie' in request.cookies %} + <b>{{ request.cookies['cookie'] }}</b> + {% else %} + not set + {% endif %} +</p> +<p><a href="{{ url_for('text') }}">Click here</a> to view a page that + contains plain text</p> +<p><a href="{{ url_for('xml') }}">Click here</a> to view a page that + contains XML data</p> +<p><a href="{{ url_for('json') }}">Click here</a> to view a page that + contains JSON data </p> +<p><a href="{{ url_for('redir') }}">Click here</a> to view a page that + redirect to the plain text page</p> +<p><a href="{{ url_for('cookie') }}">Click here</a> to view a page that sets + a cookie and then redirect back to this page +</p> +<p><a href="{{ url_for('response') }}">Click here</a> to view a page + that shows plain text through a response object.</p> \ No newline at end of file @@ -0,0 +1,2 @@ +This page contains plain text. +Use your back button to go back to the index page. \ No newline at end of file