Flask 学习笔记(1) --- 搭建你的第一个 web server

栏目: Python · 发布时间: 6年前

开发环境

  • 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 的示例, 开始编写第一个 server

    from 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 即可访问网站, 页面的内容就是 Hello

    python3 main.py

编写 IndexHandler

  • 在上一节中, 我们使用了 @ decorator 来指定某个路由对应的处理函数, 这样的写法非常方便. 同时, 我们也可以编写我们自己的 Handler 来处理各个不同的页面(路径). 比如, 对于首页 Index , 即 http://server_ip:8080/ , 我们可以编写一个 class IndexHandler , 注意这是一个 MethodView 的子类, 也就是说这是一个 View Handler

    from 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 request

    python3 main.py

参考资料


以上所述就是小编给大家介绍的《Flask 学习笔记(1) --- 搭建你的第一个 web server》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beautiful Code

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》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具