python & go 語言完成最簡單的web應用

徒手使用python和go語言搭建最簡單的web頁面-使用模板,無持久化php


也許咱們會接觸到不少語言的web應用,譬如php,java,包括今天介紹的python和go,實際上咱們在使用這些語言構建web應用的時候,不少時候變成了單純的調用包和api,而忽略底層的原理。
不過呢,全部的web應用,模型都是一致的。
瀏覽器發送一個http請求;
服務器收到請求,生成一個html頁面,做爲body返回給客戶端;
客戶端解析對應的html頁面。html

搞清楚這個簡單的邏輯,咱們就能夠垂手可得開發web應用了。java

先說python版本:python

#!/usr/bin/env python
# -*- coding: utf-8 -*-web

from flask import Flask, request, render_template數據庫

app = Flask(__name__)flask

@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('TODO.html',view="happy")api

if __name__ == '__main__':
app.run(host='', port=8000, debug=True)瀏覽器


代碼的前兩行是註釋,也是必須包含的代碼。
第一行表明這是python可執行腳本。
第二行表明編碼是utf-8。服務器

下一行表明引入的包。表明從flask包裏面引入Flask、request、render_template這三個包。
鑑於咱們是作web應用,因此我介紹一下flask。
https://book.douban.com/subject/26274202/
flask 依賴兩個外部庫: Jinja2 模板引擎和 Werkzeug WSGI 工具集。Jinja2模板引擎是python web 經常使用的模板引擎,相似於smarty之於php。WSGI是python網絡開發的基礎工具,不作過多贅述。

下一行代碼。
因爲這裏使用的是單一模塊,因此使用__name__(值爲"__main__"),這一行代碼至關於定義了一個,模塊

下面三行代碼,包括一行裝飾器和兩行函數。裝飾器代表在默認路徑下進入該函數。
對於該函數執行模板TODO.html,並傳遞view的值。

最後兩行表明該模塊只有在被python解釋器解釋時才能執行(避免做爲模塊)

而後講使用Go語言

go語言我寫的比較麻煩:
package main
import (
"html/template"
"log"
"net/http"
)

const (
username = "root"
userpwd = ""
dbname = "gooo"
)

// User is user
type User struct {
ID string
Name string
}

// 單獨提出來,渲染模板
func render(w http.ResponseWriter, tmplName string, context map[string]interface{}) {

// tmpl := template.New("index.html")
tmpl,err:= template.ParseFiles(tmplName)
// err:=nil
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl.Execute(w, nil)
return
}


//home界面
func indexHandler(w http.ResponseWriter, r *http.Request) {
_, err := getDB(username, userpwd, dbname)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//locals能夠做爲模板變量去渲染,這裏我沒有使用
locals := make(map[string]interface{})
users := []User{}
locals["users"] = users
render(w, "./index.html",nil)
return
}


//用來寫獲取數據庫的鏈接配置,並未真正實現
func getDB(username, userpwd, dbname string)( int,error) {
return 123,nil
}

func main() { //綁定 http.HandleFunc("/", indexHandler) //綁定端口 err := http.ListenAndServe(":8880", nil) if err != nil { log.Fatal("ListenAndServe: ", err.Error()) }}

相關文章
相關標籤/搜索