Web 開發學習筆記(1) --- 搭建你的第一個 Web Server

簡介

Flask 是一個輕量級的 Web 框架, 若是要學習 Web 開發, Flask 很是適合做爲咱們學習的起點.python

經過接下來的這一些列的博客, 咱們將學習如何利用 Flask 以及其餘工具, 搭建一個簡單的網站. git

We'll build a web application from scratch. Have fun :)github


開發環境

  • Ubuntu 16.04

    Python 3.5web

    Flask 1.0.2flask

  • 命令以下api


    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, 並在其中新建一個 server.py 文件瀏覽器


    mkdir ~/webapp
    cd ~/webapp
    touch server.py
  • 接着, 咱們打開 server.py, 按照 Flask Quickstart 的示例, 開始編寫第一個 serverbash


    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 便可訪問網站, 頁面的內容就是 Helloapp


    python3 server.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 server.py


參考資料

相關文章
相關標籤/搜索