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

Posted DRQ丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 = <h1>Hello %s!</h1> % 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/<int:year>)
def go_back(year):
    return "<h1>welcome to %d"%(2018-year)


@app.route(/colors/<any(blue, white, red):color>)
def three_color(color):
    return "<p>Love is patient and kind. Love is not jealous or boastful or pround or rude.</p>"


@app.route(/brew/<drink>)
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/<content_type>)
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 = ‘‘‘<!DOCTYPE html>
<html>
<head></head>
<body>
  <h1>Note</h1>
  <p>to: Peter</p>
  <p>from: Jane</p>
  <p>heading: Reminder</p>
  <p>body: <strong>Don‘t forget the party!</strong></p>
</body>
</html>
‘‘‘
        response = make_response(body)
        response.mimetype = text/html
    elif content_type == xml:
        body = ‘‘‘<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Peter</to>
  <from>Jane</from>
  <heading>Reminder</heading>
  <body>Don‘t forget the party!</body>
</note>
‘‘‘
        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/<name>)
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 <h1>Foo page</h1><a href="%s"> Do something and redirect</a>            % url_for(do_something, next=request.full_path)


@app.route(/bar)
def bar():
    return <h1>Bar page</h1> <a href="%s"> Do something and redicrect</a>            % 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 ‘‘‘
    <h1>A very long post</h1>
    <div class="body">%s</div>
    <button id="load">Load More</button>
    <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $(‘#load‘).click(function(){
            $.ajax({
                url:‘/more‘,
                type:‘get‘,
                success:function(data){
                    $(‘.body‘).append(data);
                }
            })
        })
    })
    </script>‘‘‘ % post_body


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

 

以上是关于flaskweb开发实战,入门进阶和原理解析第二章,http部分实例的主要内容,如果未能解决你的问题,请参考以下文章

分享《Flask Web开发实战:入门进阶与原理解析》PDF+源代码

《Flask Web开发实战:入门进阶与原理解析》读书笔记

flask web开发实战 入门进阶和原理解析

Flask Web开发实战(入门进阶与原理解析)

Python开发实战资料分享:《Flask Web开发实战:入门进阶与原理解析》PDF+源代码

书籍《Flask Web开发实战:入门进阶与原理解析》,相关资料网址