Try   HackMD

Bottle與Python內建wsgi

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
回筆記首頁

tags: python bottle wsgi

WSGI (Web Server Gateway Interface) Bottle 是一個很小的 Python wsgi server (Web Server Gateway Interface),較內建的wsgi server可以快速開發app。 我們先介紹Python內建Wsgi Server,再介紹Bottle

1. python內建wsgi

新增wsgi.py,內容如下

from wsgiref.simple_server import make_server def application(environ, start_response): status = '200 OK' headers = [('Content-Type', 'text/html; charset=utf8')] start_response(status, headers) return [b'Hello, World!'] if __name__ == '__main__': print('Starting server now...') try: httpd = make_server('127.0.0.1', 8000, application) print('Successful! Press Ctrl-C to stop the server.') httpd.serve_forever() except: print('Stop service!')

在python環境中執行 python wsgi.py
http://127.0.0.1:8000
Hello World! [成功!!!]
但這個陽春的wsgi使用起來卻極不方便,自己要處理Get、Post與傳入參數。
因此我們建議使用現成的wsgi模組。
常用的模組有 Bottle、Flask與Django:
Flask有wsgi與asgi模組,如果需要使用到asgi又不想寫太大的架構,Flask是最佳的選擇。
Bottle只有wsgi功能,極小需要且不再安裝其他模組、只有一個py檔,因此很適合拿來寫 Bot的app,而且它還內建http server。
Django是一個高級的 Python 網路框架,可以快速開發安全和可維護的網站。由經驗豐富的開發者構建,Django 負責處理網站開發中麻煩的部分,因此你可以專注於編寫應用程序,而無需重新開發。Django有多受歡迎? 有名的Pinterest與Instagram都是以Django所開發的,不過它的學習曲線最難。

2. Bottle 模組

使用 Bottle,要先安裝 pip install bottle

2-1: Hello World! 第一個bottle app

新增 app.py

from bottle import Bottle, run app=Bottle() @app.route('/') def hello(): return "Hello World!" run(app,host='localhost', port=8000, debug=True)

它與使用內建的wsgi的程式碼簡化許多,且易懂易讀

2-2: 除了Hello World外,新增一些功能

新增 app1.py

from bottle import Bottle, template, run app=Bottle() @app.route('/') @app.route('/hello/<name>') def hello(name='World'): return template('Hello {{name}}!', name=name) run(app,host='localhost', port=8001, debug=True)

測試 http://localhost:8000/http://localhost:8001/hello/whsh

相關連結
Flask
Django

Author:

  • 林奇賢