开发环境
-
Ubuntu 16.04
Python 3.5
Flask 1.0.2
-
命令如下
sudo apt-get upgrade sudo apt-get install python3-setuptools sudo apt-get install python3-dev sudo apt-get install python3-pip sudo pip3 install pip --upgrade sudo pip3 install flask
第一个 server
-
首先我们创建一个文件夹
webapp, 并在其中新建一个main.py文件mkdir ~/webapp cd ~/webapp touch main.py
-
接着, 我们打开
main.py, 按照 Flask Quickstart 的示例, 开始编写第一个serverfrom flask import Flask app = Flask(__name__) @app.route('/', methods=['GET']) # methods 默认是 GET 因此可以简写为如下形式 # @app.route('/') def hello(): return 'Hello' if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True)保存文件后, 在
Terminal中输入如下命令, 即可运行webapp. 我们在浏览器中输入http://server_ip:8080即可访问网站, 页面的内容就是Hellopython3 main.py
编写 IndexHandler
-
在上一节中, 我们使用了
@ decorator来指定某个路由对应的处理函数, 这样的写法非常方便. 同时, 我们也可以编写我们自己的Handler来处理各个不同的页面(路径). 比如, 对于首页Index, 即http://server_ip:8080/, 我们可以编写一个class IndexHandler, 注意这是一个MethodView的子类, 也就是说这是一个View Handlerfrom flask import Flask from flask.views import MethodView app = Flask(__name__) class IndexHandler(MethodView): def __init__(self, name): print(name) def get(self): return 'It is a GET request' def post(self): return 'It is a POST request' if __name__ == '__main__': app.add_url_rule('/', view_func=IndexHandler.as_view('index')) app.run(port=8080, host='0.0.0.0', debug=True)根据 flask docs , 传给
as_view()的参数name会转发给构造函数, 我们暂时用不到这个参数name, 但是为了保持命名的一致性, 我们将其设置为index -
保存文件后, 在
Terminal中输入如下命令, 即可运行webapp. 我们在浏览器中输入http://server_ip:8080即可访问网站, 页面的内容是It is a GET requestpython3 main.py
参考资料
以上所述就是小编给大家介绍的《Flask 学习笔记(1) --- 搭建你的第一个 web server》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:- Boa+CGI环境搭建笔记
- Go学习笔记01-环境搭建
- Nginx学习笔记(反向代理&搭建集群)
- Flutter macOS 开发环境搭建笔记
- 使用 Github + VNote 搭建个人笔记
- Go语言笔记 | 02-开发环境搭建
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Beautiful Code
Greg Wilson、Andy Oram / O'Reilly Media / 2007-7-6 / GBP 35.99
In this unique work, leading computer scientists discuss how they found unusual, carefully designed solutions to difficult problems. This book lets the reader look over the shoulder of major coding an......一起来看看 《Beautiful Code》 这本书的介绍吧!