全部Flask程序必须有一个程序实例html
Flask调用视图函数后,会将视图函数的返回值做为响应的内容,返回给客户端。通常状况下,响应内容主要是字符串和状态码。python
当客户端想要获取资源时,通常会经过浏览器发起HTTP请求。此时,Web服务器使用WSGI(Web Server Gateway Interface)协议,把来自客户端的全部请求都交给Flask程序实例。WSGI是为 Python 语言定义的Web服务器和Web应用程序之间的一种简单而通用的接口,它封装了接受HTTP请求、解析HTTP请求、发送HTTP,响应等等的这些底层的代码和操做,使开发者能够高效的编写Web应用。正则表达式
程序实例使用Werkzeug来作路由分发(URL请求和视图函数之间的对应关系)。根据每一个URL请求,找到具体的视图函数。 在Flask程序中,路由的实现通常是经过程序实例的route装饰器实现。route装饰器内部会调用add_url_route()方法实现路由注册。flask
调用视图函数,获取响应数据后,把数据传入HTML模板文件中,模板引擎负责渲染响应数据,而后由Flask返回响应数据给浏览器,最后浏览器处理返回的结果显示给客户端。浏览器
# 导入Flask类 from flask import Flask #Flask类接收一个参数__name__ app = Flask(__name__) # 装饰器的做用是将路由映射到视图函数index @app.route('/') def index(): return 'Hello World' # Flask应用程序实例的run方法启动WEB服务器 if __name__ == '__main__': app.run()
$ cd /home/python/code
$ python helloworld.py
... app = Flask(__name__, static_url_path="/python", # 访问静态资源的url前缀, 默认值是static static_folder="static", # 静态文件的目录,默认就是static template_folder="templates", # 模板文件的目录,默认是templates ) ...
app.config.from_object() 从对象中导入服务器
1 from flask import Flask 2 3 app = Flask(__name__, 4 static_url_path="/python", # 访问静态资源的url前缀, 默认值是static 5 static_folder="static", # 静态文件的目录,默认就是static 6 template_folder="templates", # 模板文件的目录,默认是templates 7 ) 8 9 # 配置参数的使用方式 10 # 1. 使用配置文件 11 app.config.from_pyfile("config.cfg") 12 13 14 @app.route("/") 15 def index(): 16 """定义的视图函数""" 17 return "helloworld" 18 19 20 if __name__ == '__main__': 21 # 启动flask程序 22 app.run()
# config.cfg 文件 DEBUG = True
这样你从新运行一下app
建立一个类,来定义类属性为配置项框架
# coding:utf-8 from flask import Flask app = Flask(__name__, static_url_path="/python", # 访问静态资源的url前缀, 默认值是static static_folder="static", # 静态文件的目录,默认就是static template_folder="templates", # 模板文件的目录,默认是templates ) # 2. 使用对象配置参数 class Config(object): DEBUG = True # 使用方法加载设置的配置 app.config.from_object(Config) @app.route("/") def index(): """定义的视图函数""" return "hello world" if __name__ == '__main__': # 启动flask程序 app.run()
from flask import Flask app = Flask(__name__, static_url_path="/python", # 访问静态资源的url前缀, 默认值是static static_folder="static", # 静态文件的目录,默认就是static template_folder="templates", # 模板文件的目录,默认是templates ) # 3. 直接操做config的字典对象 app.config["DEBUG"] = True @app.route("/") def index(): return "hello flask" if __name__ == '__main__': # 启动flask程序 app.run()
1.若是你在当前能访问到app的状况下函数
app.config.get("DEBUG")post
2.若是你没法拿到app这个对象时,你只须要导入current_app,也是能够拿到配置信息的
current_app.config.get("DEBUG")
from flask import Flask, current_app @app.route("/") def index(): """定义的视图函数""" # 读取配置参数 # 1. 直接从全局对象app的config字典中取值 # print(app.config.get("ITCAST")) # 2. 经过current_app获取参数 # print(current_app.config.get("ITCAST")) return "hello flask"
if __name__ == '__main__': # 启动flask程序 # app.run() app.run(host="0.0.0.0", port=5000, debug=True) # port指定的端口,debug 是惟一能够指定在这里的配置项
你在开发的状态下,若是局域网中不须要别的主机访问,你能够不指定(host),若是你想在同一局域网中,别的主机也能够访问到,而且你本身还想以回环地址(127.0.0.1)访问的话就能够指定为‘0.0.0.0’
扩展: 0.0.0.0
IPV4中,0.0.0.0地址被用于表示一个无效的,未知的或者不可用的目标。
* 在服务器中,0.0.0.0指的是本机上的全部IPV4地址,若是一个主机有两个IP地址,192.168.1.1 和 10.1.2.1,而且该主机上的一个服务监听的地址是0.0.0.0,那么经过两个ip地址都可以访问该服务。
* 在路由中,0.0.0.0表示的是默认路由,即当路由表中没有找到彻底匹配的路由的时候所对应的路由。用途总结:
- 当一台主机尚未被分配一个IP地址的时候,用于表示主机自己。(DHCP分配IP地址的时候)
- 用做默认路由,表示”任意IPV4主机”。
- 用做服务端,表示本机上的任意IPV4地址。
from flask import Flask, current_app app = Flask(__name__, static_url_path="/python", # 访问静态资源的url前缀, 默认值是static static_folder="static", # 静态文件的目录,默认就是static template_folder="templates", # 模板文件的目录,默认是templates ) class Config(object): DEBUG = True app.config.from_object(Config) @app.route("/") def index(): """定义的视图函数""" return "hello flask" if __name__ == '__main__': # 启动flask程序 print(app.url_map) # 打印路由的详情 app.run()
(Flask_py) python@python-VirtualBox:~/code$ python hello.py # 首先'/' 是咱们index定义的路由规则 # (HEAD, OPTIONS, GET)能够经过元组中这三种方式访问 # index是指定的视图函数 Map([<Rule '/' (HEAD, OPTIONS, GET) -> index>, # /python/<filename> 这是访问静态页面的路由规则 # (HEAD, OPTIONS, GET)默认的访问方式 # static 静态资源 <Rule '/python/<filename>' (HEAD, OPTIONS, GET) -> static>]) * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat
...
@app.route('/post_only', methods=['POST']) def post_only(): return 'post method page'
...
...
@app.route('/post_only', methods=['GET','post']) def post_only(): return 'post method page'
...
# 这里咱们有两个视图分别为hello一、hello2 @app.route('/hello') def hello1(): return 'This is a hello 1' @app.route('/hello') def hello2(): return 'This is a hello 2'
<Rule '/hello' (HEAD, OPTIONS, GET) -> hello1>, <Rule '/hello' (HEAD, OPTIONS, GET) -> hello2>,
# 这里咱们分别给hello一、hello2设置了请求方式 @app.route('/hello', methods=['POST']) def hello1(): return 'This is a hello 1' @app.route('/hello', methods=['GET']) def hello2(): return 'This is a hello 2'
# 定义了一个视图为test @app.route('/test1') @app.route('/test2') def test(): return 'two routes are used for one page'
# 导入redirect来实现页面重定向 from flask import Flask, current_app, redirect ... @app.route("/") def index(): """定义的视图函数""" return "index page" # 建立一个login视图,当执行完毕后直接返回到index页面 @app.route('/login') def login(): # 定义index视图的路径 url = '/' return redirect(url) ...
# 优化代码,使用反向解析来实现跳转到 index 页面 from flask import Flask, current_app, redirect, url_for ... @app.route("/") # 当这里路径更改以后,下面login视图中的地址也不须要改变 def index(): return "index page" @app.route('/login') def login(): url = url_for('index') return redirect(url) ...
int | 接受整数 |
float | 接收浮点数 |
path | 和默认的相同,但也接受斜线 |
# 这里指定int,尖括号中冒号后面的内容是动态的 @app.route('/user/<int:id>') def user(id): return '欢迎id: %d的用户' %id
# 127.0.0.1:5000/user/hannibal @app.route('/user/<username>') def user(username): return '欢迎 %s ' %username
from flask import Flask, current_app, redirect, url_for from werkzeug.routing import BaseConverter # 咱们须要继承的转换器类 app = Flask(__name__) class RegexConverter(BaseConverter): """自定义转换器类""" def __init__(self, url_map, regex): # 调用父类的初始化方法 这里咱们须要将url_map传给父类 super(RegexConverter, self).__init__(url_map) # 将正则表达式的参数保存到对象的属性中,flask会去使用这个属性来进行路由的正则匹配 self.regex = regex # 这个就是咱们规定的正则匹配的规则 r'1[34578]\d{9}' self.regex是固定的写法 # 将自定义的转换器添加到flask的应用中
# 这里咱们向converters这个字典中添加了一个re键对应咱们的转换器,re本身能够随便命名 app.url_map.converters['re'] = RegexConverter # 这里模拟匹配手机号码 # 127.0.0.1:5000/send/138XXXXXXXX @app.route("/send/<re(r'1[34578]\d{9}'):phone_num>") def send_sms(phone_num): return "send message to %s" % phone_num if __name__ == '__main__': # 查看路由信息 print(app.url_map) # 启动flask程序 app.run(debug=True)
from flask import Flask from werkzeug.routing import BaseConverter app = Flask(__name__) class RegexConverter(BaseConverter): """自定义转换器类""" def __init__(self, url_map, regex): # 调用父类的初始化方法 这里咱们须要的第二个参数就是传给父类 super(RegexConverter, self).__init__(url_map) # 将正则表达式的参数保存到对象的属性中,flask会去使用这个属性来进行路由的正则匹配 print('init 执行了') self.regex = regex # 定义一个实例属性存储原手机号和加密后的手机号 self.phone = [] def to_python(self, value): print('to_python 执行了') # 将原有的手机号码存入集合中 self.phone.append(value) # 自制加密 self.value = value[0:8] + "XXXX" # 将加密的数据存入集合中 self.phone.append(self.value) return self.phone # 将自定义的转换器添加到flask的应用中 app.url_map.converters['re'] = RegexConverter # 这里模拟匹配手机号码 # 127.0.0.1:5000/send/138XXXXXXXX @app.route("/send/<re(r'1[34578]\d{9}'):phone_num>") def send_sms(phone_num): original_number = phone_num[0] encrypted_data = phone_num[1] return "%s send message to %s" % (original_number, encrypted_data) if __name__ == '__main__': # 查看路由信息 print(app.url_map) # 启动flask程序 app.run(debug=True)
from flask import Flask, current_app, redirect, url_for from werkzeug.routing import BaseConverter app = Flask(__name__) class RegexConverter(BaseConverter): """自定义转换器类""" def __init__(self, url_map, regex): # 调用父类的初始化方法 这里咱们须要的第二个参数就是传给父类 super(RegexConverter, self).__init__(url_map) # 将正则表达式的参数保存到对象的属性中,flask会去使用这个属性来进行路由的正则匹配 print('init 执行了') self.regex = regex self.phone = [] def to_python(self, value): print('to_python 执行了') self.phone.append(value) self.value = value[0:8] + "XXXX" self.phone.append(self.value) return self.phone def to_url(self, value): print('to_url 执行了') return value # 将自定义的转换器添加到flask的应用中 app.url_map.converters['re'] = RegexConverter # 这里模拟匹配手机号码 # 127.0.0.1:5000/send/138XXXXXXXX @app.route("/send/<re(r'1[34578]\d{9}'):phone_num>") def send_sms(phone_num): print('send_sms 视图函数执行') original_number = phone_num[0] encrypted_data = phone_num[1] return "%s send message to %s" % (original_number, encrypted_data) @app.route('/') def index(): # 使用反向解析到咱们定义的send_sms视图函数 # 由于路径匹配规则中有phone_num 因此这里咱们须要传参 print('index') url = url_for('send_sms', phone_num='18000000000') return redirect(url) if __name__ == '__main__': # 查看路由信息 print(app.url_map) # 启动flask程序 app.run(debug=True)
后台查看一下执行流程: