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/') #如果这里有可选参数,则需要注意下方需要定义一个函数来处理参数
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 "Hello World!
"
但是代码会显示的稍微复杂一些,这里就需要用到Templates.
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $mkdir templates
┌─[thekingofnight@parrot]─[~/flask]
└──╼ $vi templates/base_page.html
写入以下内容
Test Flask
Hello World!
修改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/
Test Flask
Hello World!
简单的扩展
案例一
hello-world.py
#!/usr/bin/env python3
"""Out first Flask Application"""
from flask import Flask,render_template
app = Flask("__name__")
@app.route('/')
def hello(name):
return render_template('base_page.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)
/templates/base_page.html
Test Flask
Hello {{name}}!
访问 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('/')
def hello(name):
return render_template('base_page.html',name=name)
if (__name__=="__main__"):
app.run(debug=False)
/templates/base_page.html
Test Flask
{% if name %}
Hello {{name}}!
{% else %}
Hello World!
{% endif %}
访问 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('/')
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('/')
def hello(name=None):
return render_template('home.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)
/templates/base_page.html
Test Flask
{% block content %}{% endblock %}
/templates/home.html
{% extends "base_page.html" %}
{% block content%}
Welcome to my Blog.
This is home page.
{% endblock %}
访问 http://127.0.0.1:5000/ 即可得到如下效果
Test Flask
Welcome to my Blog.
This is home page.
静态文件的加载
这里直接给出案例
┌─[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('/')
def hello(name=None):
return render_template('home.html',name=name)
if (__name__=="__main__"):
app.run(debug=True)
/templates/base_page.html
Test Flask
{% block content %}{% endblock %}
/templates/home.html
{% extends "base_page.html" %}
{% block content%}
Welcome to my Blog.
This is home page.
{% 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/
Test Flask
Welcome to my Blog.
This is home page.
参考
http://flask.pocoo.org/docs/1.0/*
https://www.youtube.com/watch?v=bNSz29Iqpxc&list=PL1H1sBF1VAKVtrhim9EDG7vFarkbo4V0C