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)

原文地址:https://www.cnblogs.com/dairuiquan/p/10328129.html

时间: 2024-07-31 10:58:49

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

微信开发实战入门视频教程(Android4.4.2)

基于移动技术微信公众平台开发实战入门(Android4.4.2,微移动应用,项目实战) 适合人群:初级课时数量:40课时用到技术:微移动应用涉及项目:手机微信开发 qq:1840215592 课程内容简介微信腾讯公司推出的一个即时通讯服务的应用,微信提供公众平台.朋友圈.消息推送等功能,预计到2014年年底其注册用户量将突破10亿.面对一个用户数如此巨大的家伙,大家怎么能放过,都迫不及待的希望自己的应用能够跟微信产生一些联系.那么我们这套课程要讲的就是如何跟微信产生连接,如何将我们的网站接入到微

Laravel 教程 - Web 开发实战入门 ( Laravel 5.5 )购买链接

? Laravel 教程 - Web 开发实战入门 ( Laravel 5.5 )购买链接: 推荐给你高品质的实战课程 https://laravel-china.org/courses?rf=15818 ? ? 文章来源:刘俊涛的博客 欢迎关注,有问题一起学习欢迎留言.评论. 原文地址:https://www.cnblogs.com/lovebing/p/9578193.html

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

URL重定向 错误响应 > 如果你想手动返回错误响应,可以使用Flask提供的abort()函数. XML 原文地址:https://www.cnblogs.com/plusUltra/p/10551555.html

thinkphp5开发快速入门 进阶

我整理了一下继thinkphp5开发手册之后的 路由.控制器.模型的手册,整合成了一个chm文件.绝对够大家开发thinkphp5使用的. 防止下载泛滥,象征性的设置了一个下载币. 如果没有下载币,可以在下面留言邮箱,我发你邮箱. thinkphp5开发手册合集

《java开发实战经典》读书笔记——第3章 Java基础程序设计之数据类型划分20151026

数据类型 基础数据类型 数值型 整数类型 浮点类型 字符型 布尔型 引用数据类型 类 接口 数组

《算法竞赛入门经典——训练指南》第二章题库

UVa特别题库 UVa网站专门为本书设立的分类题库配合,方便读者提交: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=442 注意,下面注有"extra"的习题并没有在书中出现,但在上面的特别题库中有,属于附加习题. 基础练习 (Basic Problems) UVa11388 GCD LCM UVa11889 Benefit UVa10943 How do y

数据库系统原理(第二章关系数据库 )

一.关系数据库概述 20世纪80年代后,在商用数据库管理系统中,( 关系模型 )逐渐取代早 期的网状模型和层次模型,成为主流数据模型 二.关系数据模型 数据模型的要素包括:数据结构.数据操作.数据约束 关系数据模型的组成要素: 关系数据结构 表(Table): 也称为关系,是一个二维的数据结构,由表名.列.若干行数据组成:每个表有唯一的表名,表中每一行数据描述一条具体的记录值 关系(Relation): 一个关系逻辑上对应一张二维表,可以为每个关系取一个名称进行表示.基本关系 (基本表. 基表)

Java类加载原理解析

1       基本信息 摘要: 每个java开发人员对java.lang.ClassNotFoundExcetpion这个异常肯定都不陌生,这背后就涉及到了java技术体系中的类加载.Java的类加载机制是java技术体系中比较核心的部分,虽然和大部分开发人员直接打交道不多,但是对其背后的机理有一定理解有助于排查程序中出现的类加载失败等技术问题,对理解java虚拟机的连接模型和java语言的动态性都有很大帮助. 由于关于java类加载的内容较多,所以打算分三篇文章简述一下: 第一篇:java类

Node.js继承中的静态类对象(《node.js开发实战详解》书中一些错误的改正)

今天气真好,最近挂掉一些面试之后心情略失落. 神马都是浮云,要永远做好世界第二. 不多提了,你问我心态为啥变好了.-------都是情怀,,. 嗯啊,最近在研究node. 别人问?你这水平还node... 哈哈哈,好伤心.... 不多提了,言归正传. 神马模块化神马的先就不多讲了,就一个module.export和export区别,后者对象的属性属于前者,逆命题不成立. 还有util.inherits(A,B)这个API注意一下A只会继承B的原型方法,原型以外的不会继承.不是说原型中数据是共享的