Flask学习笔记

python Flask逐渐变的流行,有必要学习一哈,这里给予我浅显的一点讲解,如果理解不到位的地方,希望各位师傅斧正,感激不尽。


环境准备

sudo apt install python-pip
sudo pip3 install flask

mkdir flask
cd flask/

开始

hello-world.py

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask
app = Flask("__name__")  #这里以接受包或者模块为参数,一般传递__name__
                         #这里定义了变量app赋值为Flask()

@app.route('/')         #这里相当于定义了一个路由,具体访问一下本地就知道了
def index():            #路由的函数就是紧接着定义的函数
  return "Hello World!" #访问http://127.0.0.1:5000/(默认端口)界面返回Hello World!

@app.route('/say_hello')
def say_hello():
  return "Hello You are so Good!"  #访问http://127.0.0.1:5000/say_hello界面返回Hello You are so Good!

if (__name__=="__main__"):
  app.run()  #端口可以修改app.run(host='0.0.0.0',port=8000)

一个非常简单的flask网页就已经搭建成功,直接运行该python程序

┌─[thekingofnight@parrot]─[~/flask]
└──╼ $chmod +x hello-world.py 
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $sudo ./hello-world.py 
 * Serving Flask app "__name__" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

当然也可以这样,效果是一样的

┌─[thekingofnight@parrot]─[~/flask]
└──╼ $FLASK_APP=hello-world.py flask run
* Serving Flask app "hello-world"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

这里可以看到一些信息,并且可以看到Debug模式是关闭的,端口开放。
直接访问就好。
另外用户访问的信息都会显示在终端。

127.0.0.1 - - [28/Sep/2018 11:40:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [28/Sep/2018 11:40:41] "GET /aaa HTTP/1.1" 404 -
127.0.0.1 - - [28/Sep/2018 11:40:55] "GET /%60 HTTP/1.1" 404 -
127.0.0.1 - - [28/Sep/2018 11:40:59] "GET /_ HTTP/1.1" 404 -

直接访问 http://127.0.0.1:5000/ 就可以看到简单的页面。

Debug Mode

这里Debug模式可以开启,直接修改

if (__name__=="__main__"):
  app.run(debug=True) 
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $./hello-world.py 
 * Serving Flask app "__name__" (lazy loading)
 * Environment: production
   WARNING: Do not use the development server in a production environment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 298-xxx-xx1

开启debug模式,可以看到这里会返回我们的pin码,18年安恒杯8月赛题目好像有一道
关于计算PIN码的,有兴趣的师傅们可以去看看。
所以将flask框架制作完成的产品放制到公网上时,千万不要开启Debug模式

简单的拓展

@app.route('/say_hello/<name>') #如果这里有可选参数,则需要注意下方需要定义一个函数来处理参数
def say_hello_to_someone(name):
  return "Hello %s!"%name
------------------------------------------------------------------------------------------
然后访问http://127.0.0.1:5000/say_hello/theKingOfNight
界面返回Hello theKingOfNight!
------------------------------------------------------------------------------------------

这里添加的参数支持4种类型

string  (default) accepts any text without a slash
int accepts positive integers
float   accepts positive floating point values
path    like string but also accepts slashes
uuid    accepts UUID strings

Templates简介

在python中直接可以返回相应的html代码,例如

@app.route('/')
def index():
  return "<h1>Hello World!</h1>"

但是代码会显示的稍微复杂一些,这里就需要用到Templates.

┌─[thekingofnight@parrot]─[~/flask]
└──╼ $mkdir templates
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $vi templates/base_page.html 

写入以下内容

<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
</head>
<body>
    <p>Hello World!</p>
</body>
</html>

修改hello-world.py为

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")  

@app.route('/')         
def index():            
  return render_template('base_page.html') 

if (__name__=="__main__"):
  app.run(debug=True)

访问 view-source:http://127.0.0.1:5000/


<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
</head>
<body>
    <p>Hello World!</p>
</body>
</html>

简单的扩展

案例一

hello-world.py

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")  


@app.route('/<name>')         
def hello(name):            
  return render_template('base_page.html',name=name) 


if (__name__=="__main__"):
  app.run(debug=True)

/templates/base_page.html

<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
</head>
<body>
    <p>Hello {{name}}!</p>
</body>
</html>

访问 http://127.0.0.1:5000/theKingOfNight 即可显示出 Hello theKingOfNight!

案例二

hello-world.py

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")  

@app.route('/<name>')         
def hello(name):            
  return render_template('base_page.html',name=name) 

if (__name__=="__main__"):
  app.run(debug=False)

/templates/base_page.html

<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
</head>
<body>
    <p>
    {% if name %}
    Hello {{name}}!
    {% else %}
    Hello World!
    {% endif %}
    </p>
</body>
</html>

访问 http://127.0.0.1:5000/theKingOfNight

可以同样输出 Hello theKingOfNight!

案例三

hello-world.py

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")  


@app.route('/')
@app.route('/<name>')         
def hello(name=None):            
  return render_template('base_page.html',name=name) 


if (__name__=="__main__"):
  app.run(debug=True)

/templates/base_page.html同上

访问 http://127.0.0.1:5000/ 即可输出 Hello World!
访问 http://127.0.0.1:5000/theKingOfNight 输出Hello theKingOfNight!

案例四 (继承)

hello-world.py

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")  


@app.route('/')
@app.route('/<name>')         
def hello(name=None):            
  return render_template('home.html',name=name) 


if (__name__=="__main__"):
  app.run(debug=True)

/templates/base_page.html

<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Contact</a></li>
            <li><a href="#">About</a></li>
        </ul>
    </nav>
    <p>
        {% block content %}{% endblock %}
    </p>
</body>
</html>

/templates/home.html

{% extends "base_page.html" %}
{% block content%}
    <h1>Welcome to my Blog.</h1>
    <p>
        This is home page.
    </p>
{% endblock %}

访问 http://127.0.0.1:5000/ 即可得到如下效果


<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Contact</a></li>
            <li><a href="#">About</a></li>
        </ul>
    </nav>
    <p>
    <h1>Welcome to my Blog.</h1>
    <p>
        This is home page.
    </p>
    </p>
</body>
</html>

静态文件的加载

这里直接给出案例

┌─[thekingofnight@parrot]─[~/flask]
└──╼ $mkdir static
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $cd static/
┌─[thekingofnight@parrot]─[~/flask/static]
└──╼ $mkdir img css font
┌─[thekingofnight@parrot]─[~/flask/static]
└──╼ $ls
css  font  img

hello-world.py

#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")  


@app.route('/')
@app.route('/<name>')         
def hello(name=None):            
  return render_template('home.html',name=name) 


if (__name__=="__main__"):
  app.run(debug=True)

/templates/base_page.html

<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/stylesheet.css')}}">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Contact</a></li>
            <li><a href="#">About</a></li>
        </ul>
    </nav>
    <p>
        {% block content %}{% endblock %}
    </p>
</body>
</html>

/templates/home.html

{% extends "base_page.html" %}
{% block content%}
    <h1>Welcome to my Blog.</h1>
    <p>
        This is home page.
    </p>
    <img src="{{url_for('static',filename='img/test.png')}}">
{% endblock %}

/static/css/stylesheet.css

html{
    width: 600px;
    margin: 0 auto;
}

body{
    border-left: 1px solid silver;
    border-right: 1px solid silver;
}

访问 view-source:http://127.0.0.1:5000/


<!DOCTYPE html>
<html>
<head>
    <title>Test Flask</title>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="/static/css/stylesheet.css">
</head>
<body>
    <nav>
        <ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Contact</a></li>
            <li><a href="#">About</a></li>
        </ul>
    </nav>
    <p>
        
    <h1>Welcome to my Blog.</h1>
    <p>
        This is home page.
    </p>
    <img src="/static/img/test.png">

    </p>
</body>
</html>

参考

http://flask.pocoo.org/docs/1.0/*
https://www.youtube.com/watch?v=bNSz29Iqpxc&list=PL1H1sBF1VAKVtrhim9EDG7vFarkbo4V0C

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容