文章目录
- 一、flask的安装
- 安装
- 二、flask入门
- 1、hello world
- 2、run方法的参数
- 3、配置方法
- 1、直接写在run方法里
- 2、直接写一个类
- 3、写一个ini配置文件config.ini
- 4、获取配置信息
- 4、路由
- 1、基本路由设置
- 2、转换器
- 3、传入类型
- post请求数据获取
- 文件上传
- 注意点:
- 4、自定义转换器
- 1、导入父类
- 2、定义
- 3、注册
- 4、使用
- 5、重定向和错误
- redirect(),url_for()
- abort()
- errorhandler()
- 6、返回json数据
- 注
一、flask的安装
flask项目一般使用虚拟环境virtualenv运行,当然也可以直接在全局环境中使用
virtualenv的安装使用可以参考
安装
进入虚拟环境,输入指令
pip install Flask
等待安装完成即可
二、flask入门
参考文档
http://docs.jinkan.org/docs/flask/quickstart.html
1、hello world
每学习一种计算机语言首先要干的都是输出hello world
所以flask也有样学样从最简单的hello world开始
新建一个hello.py文件,写入代码
#导入了 Flask 类。这个类的实例将会是我们的 WSGI 应用程序
from flask import Flask
#接下来,我们创建一个该类的实例,第一个参数是应用模块或者包的名称。 如果你使用单一的模块(如本例),你应该使用 __name__ ,因为模块的名称将会因其作为单独应用启动还是作为模块导入而有不同( 也即是 '__main__' 或实际的导入名)。这是必须的,这样 Flask 才知道到哪去找模板、静态文件等等。详情见 Flask 的文档
app = Flask(__name__)
#然后,我们使用 route() 装饰器告诉 Flask 什么样的URL 能触发我们的函数
@app.route('/')
#这个函数的名字也在生成 URL 时被特定的函数采用,这个函数返回我们想要显示在用户浏览器中的信息
def hello_world():
return 'Hello World!'
#用 run() 函数来让应用运行在本地服务器上。 其中 if __name__ == '__main__': 确保服务器只会在该脚本被 Python 解释器直接执行的时候才会运行,而不是作为模块导入的时候
if __name__ == '__main__':
app.run()
在当前目录执行命令行
python hello.py
由于我的win7环境警告较多,不要在意,最后一条信息告诉我们服务器地址是http://127.0.0.1:5000/,另外可以ctrl+c结束服务器运行
第一个flask应用成功
2、run方法的参数
查看源码
def run(self, host=None, port=None, debug=None,
load_dotenv=True, **options):
:param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
have the server available externally as well. Defaults to
``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
if present.
:param port: the port of the webserver. Defaults to ``5000`` or the
port defined in the ``SERVER_NAME`` config variable if present.
:param debug: if given, enable or disable debug mode. See
:attr:`debug`.
:param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
files to set environment variables. Will also change the working
directory to the directory containing the first file found.
:param options: the options to be forwarded to the underlying Werkzeug
server. See :func:`werkzeug.serving.run_simple` for more
information.
host:侦听的主机ip,默认为本地回环地址127.0.0.1,设置为0.0.0.0可以让外部主机访问
port:端口号,默认为5000
debug:默认为Falase,设定为True表示打开调试模式,调试模式下服务器会自动重启读入新写入的代码
load_dotenv:加载最近的环境变量文件,同时将该文件所在目录作为工作目录
options:不定常参数,更多额外属性,不做赘述
3、配置方法
1、直接写在run方法里
2、直接写一个类
class MyConfig(object):
DEBUG = True
PORT = 5001
然后通过app.config.from_object(MyConfig)
载入
3、写一个ini配置文件config.ini
DEBUG = True
PORT = 5001
然后通过app.config.from_pyfile(‘config.ini’)
载入
4、获取配置信息
print(app.config.get('DEBUG'))
print(app.config.get('PORT'))
得到的即是True 和 5001
4、路由
1、基本路由设置
@app.route('/')
def index():
return 'Index Page'
@app.route('/world')
@app.route('/hello')
def hello():
return 'Hello World'
单一的斜杠表示只捕获到/
则返回,一般是首页
路径按照自己希望的设置即可,这里基本路由属于静态服务器
另外也可以直接装两个装饰器,为同一个视图设置两个URL
注:开头的斜杠必加
2、转换器
int 接受整数
float 同 int ,但是接受浮点数
path 和默认的相似,但也接受斜线
UUID 接受UUID
转换器的本质是:通过正则表达式匹配路由地址
@app.route('/index/<int:user_id>')
def index1 (user_id):
return 'ok'
表示路径为/index/数字整型
该写法中的user_id是获取的数字整型参数,处理函数中必须有这个参数传入的对应位置
3、传入类型
@app.route('/index/<int:user_id>',methods=['post'])
def index1 (user_id):
return 'ok'
methods用于指定传入请求方式,用列表方式指定
post请求数据获取
@app.route('/index/', methods=['POST'])
def postget():
print(request.headers) # 获取请求头
print(request.data) # 获取请求的二进制数据,图片等
print(request.form) # 这就是获取请求中的表单数据
return 'POST'
文件上传
from flask import request
@app.route('/upload', methods=[ 'POST'])
def upload_file():
f = request.files['the_file']
f.save('C:/Users/Administrator/Desktop/uploaded_file.png')
将收到的文件保存在桌面,注意the_file是上传时文件的key值,而不是默认值
注意点:
1、 Route中,用于请求方式的配置,用methods这个方法类进行指定,是一个列表,默认为GET
2、 用<>来进行参数的指定
3、 对于地址传参的问题,可以用类型来约束,如果不写,默认是string字符串
4、自定义转换器
1、导入父类
自定义转换器需要先从werkzeug.routing导入BaseConverter转换器类
from werkzeug.routing import BaseConverter
2、定义
class MyConver(BaseConverter):
def __init__ (self,parm1,*args):
""" Function doc """
print('接受传递过来的参数',parm1)
print(*args)
super().__init__(parm1)
self.regex=args[0]
3、注册
app.url_map.converters['re']=MyConver
将自定义转换器加入默认转换器字典
4、使用
@app.route('/<re("[\w]+"):name>')
def showtime(name):
return '自定义转换器的使用'
输入任何没有预设的英文字母路径都将使用该方法
5、重定向和错误
redirect(),url_for()
redirect()将用户重定向到其它地方
直接让前端定位到响应路径
from flask import redirect, url_for
@app.route('/')
def index():
return redirect(url_for('error'))
url_for()用于按照函数寻找路径,如rul_for(index)生成的是路径’/’
abort()
让用户放弃请求并返回错误代码
from flask import abort
@app.route('/error')
def error():
abort(500)
errorhandler()
一个用于自定义错误类型的装饰器
from flask import render_template
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
这里将404错误重制成一个page_not_found.html即出现404错误时返回该html页面
这样就不会单一的返回毫无意义的黑白页面,让404报错也更显个性化
当然,也可以返回一串字符串,让用户知道你需要的告知的内容
6、返回json数据
json一直都是前后端传递的重要格式
flask提供了一个非常简单的json格式转换方法jsonify
from flask import jsonify
@app.route('/')
def index():
data = {
"name": "柯南",
"age": "未知",
}
return jsonify(data)
注
不同于python的自由,json数据中必须使用双引号" "