owned this note changed 3 years ago
Published Linked with GitHub

Backend

http://homepage.ntu.edu.tw/~pollyhuang/teach/intro-cn-fall-19/slides.html

Notes

發一個 HTTP GET Request 大概像這樣:

HTTP GET HTTP/1.1\r\n
....
\r\n

Server 會回傳 Response:

HTTP/1.1 200 OK\r\n
Content-Type: text/html; charset=utf-8\r\n
Content-Length: 78\r\n
...
\r\n
<!DOCTYPE html>
<html>
.....
</html>

List of status code: 不同 status code 代表不同意義,瀏覽器收到了前端才知道要做什麼對應

Tools

Postman

EditThisCookie

Flask

官網 + 教材

https://flask.palletsprojects.com/en/1.1.x/quickstart/

Installation

$ pip install Flask

server.py

from flask import Flask, request, session, redirect app = Flask(__name__) app.secret_key = b'_5#y2L"F4Q8z\n\xec]/' @app.route('/') def hello_world(): username = session.get("username", "guest") return f'Hello, {username}' @app.route("/p", methods=["POST"]) def p(): return "post page" @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session['username'] = request.form['username'] return redirect("/") return ''' <form method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ''' if __name__ == "__main__": app.run(port=8000)
export FLASK_ENV=development
python server.py

Express

官網 + 教材

https://expressjs.com/en/starter/installing.html

Installation

$ mkdir -p backend-learn
$ cd backend-learn
$ npm init
$ npm install express --save

server.js

const express = require("express"); const app = express(); const port = 3000; app.get("/", (req, res) => { res.send("Hello World!"); }); app.post("/p", (req, res) => { res.send("post page"); }); app .route("/login") .get((req, res) => { res.send("login get"); }) .post((req, res) => { res.send("login post"); }); app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); });
export NODE_ENV=development
node server.js

auto restart

npm install nodemon
npx nodemon server.js

Cookie/Session

  • 如何做登入? -> 存東西在瀏覽器 -> Cookie
    key value pair, 一個名字一個對應值
    可以在 console 裡打 document.cookie 看到

  • 如何設定?
    登入後,server看你的帳號密碼看看是不是你,是的話就給你一串神秘字串,然後傳的時候會有下面的這樣:
    HTTP Response 會有 Set-Cookie: session="神秘字串"
    瀏覽器就會把這段放在 cookie 裡
    之後你再次發 HTTP Request 的時候就可以帶 cookie 過去,這樣 server 只要看這個神秘字串就當作你登入了,你就不用每次都重新打帳號密碼了!

/login

  • GET localhost:8000/login
    -> return html form,可以輸入 username
  • POST localhost:8000/login
    -> 拿到你的輸入,看看是不是合法的使用者

Q&A

secret key?

  • 通常會寫在 code 外面,再用環境變數灌進來,不然你 code 外流就被看光光了
  • 或者用 python 內建的 os.urandom 隨機生成

flask 內的 session(概念圖):

{ 
    # 每個 client 都會有一個 session id
    sessionid1 : { 
        username: "hello",
    },
    sessionid2 : {
        username: "haiYA, MSG"
    },
    sessionid3 : {
        username: "heyyayaya"
    }
}

Database

mongoDB
redis
SQL

補充

python decorator: 幫 function 包裝更多功能

python format string

username = "abc" f"hi {username}" # hi abc

python byte string

secret = b"sadfjfdkf" secret 是一個 byte string https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/362015/
Select a repo