flaskweb开发实战,入门进阶和原理解析第二章,http部分实例

import os
from jinja2 import escape
from flask import Flask, make_response,request, redirect,url_for,abort,session,jsonify
from urllib.parse import urlparse, urljoin
from jinja2.utils import generate_lorem_ipsum

app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', ' secret string')


# 从查询字段和cookies 获取名字
@app.route('/')
@app.route('/hello')
def hello():
    name = request.args.get('name')
    if name is None:
        name = request.cookies.get('name', 'Human')
    response = '

Hello %s!

' % escape(name) # return different response according to the user's authentication status if 'logged_in' in session: response += '[Authenticated]' else: response += '[Not Authenticated]' return response # 重定向例子 @app.route('/hi') def hi(): return redirect(url_for('hello')) # url_for表示程序内路径,去找hello函数 @app.route('/goback/') def go_back(year): return "

welcome to %d"%(2018-year) @app.route('/colors/') def three_color(color): return "

Love is patient and kind. Love is not jealous or boastful or pround or rude.

" @app.route('/brew/') def reapot(drink): if drink == 'coffee': abort(418) else: return 'a drink of tea' @app.route('/404') def not_found(): abort(404) # 返回不同的数据类型(MIME类型) @app.route('/note', defaults={'content_type': 'text'}) @app.route('/note/') def note(content_type): content_type = content_type.lower() if content_type == 'text': body = '''Note to: Peter from: Jane heading: Reminder body: Don't forget the party! ''' response = make_response(body) response.mimetype = 'text/plain' elif content_type == 'html': body = '''

Note

to: Peter

from: Jane

heading: Reminder

body: Don't forget the party!

''' response = make_response(body) response.mimetype = 'text/html' elif content_type == 'xml': body = ''' Peter Jane Reminder Don't forget the party! ''' response = make_response(body) response.mimetype = 'application/xml' elif content_type == 'json': body = {"note": { "to": "Peter", "from": "Jane", "heading": "Remider", "body": "Don't forget the party!" } } response = jsonify(body) # equal to: # response = make_response(json.dumps(body)) # response.mimetype = "application/json" else: abort(400) return response # 设置cookie @app.route('/set/') def set_cookies(name): response = make_response(redirect(url_for('hello'))) response.set_cookie('name', name) return response # 实现用户登录 2-5 @app.route('/login') def login(): session['logged_in'] = True return redirect(url_for('hello')) # 保护视图 @app.route('/admin') def admin(): if 'logged_in' not in session: abort(403) return 'welcome to admin page' @app.route('/logout') def logout(): if 'logged_in' in session: session.pop('logged_in') return redirect(url_for('hello')) # 返回上一个页面 @app.route('/foo') def foo(): return '

Foo page

Do something and redirect
'\ % url_for('do_something', next=request.full_path) @app.route('/bar') def bar(): return '

Bar page

Do something and redicrect
'\ % url_for('do_something', next=request.full_path) @app.route('/do-something') def do_something(): # do something return redirect_back() def is_safe_url(target): ref_url = urlparse(request.host_url) # 获取主机url test_url = urlparse(urljoin(request.host_url, target)) return test_url.scheme in ('http', 'https') and \ ref_url.netloc == test_url.netloc def redirect_back(default='hello', **kwargs): for target in request.args.get('next'), request.referrer: if not target: continue if is_safe_url(target): return redirect(target) return redirect(url_for('default', **kwargs)) # AJAX 点击按钮加载更多文本 @app.route('/post') def show_post(): post_body = generate_lorem_ipsum(n=2) # 生成两段随即文本 return '''

A very long post

%s
''' % post_body @app.route('/more') def load_post(): return generate_lorem_ipsum(n=1)

 

转载于:https://www.cnblogs.com/dairuiquan/p/10328129.html

你可能感兴趣的:(flaskweb开发实战,入门进阶和原理解析第二章,http部分实例)