iT邦幫忙

2024 iThome 鐵人賽

DAY 24
0
Modern Web

初學者入門 - 有人叫我寫blog那就來做吧!系列 第 24

[day-23] - 利用 vercel 部屬你的簡單應用

  • 分享至 

  • xImage
  •  

甚麼是 Vercel ?

Vercel 是一個雲端平台,專為前端開發者設計,支援靜態網站和動態網頁。Vercel 不僅可以讓你直接從你的 Git 存儲庫部署網站,還提供自動化的 CI/CD。

它的核心機制就是把你的後端應用無伺服器化Serverless,因此如果你要拿來做動態網頁,是必須要額外連線到資料庫做儲存。

小範例

這邊是我之前用來示範的一個小專案,這是利用Python FastAPI部屬的後端並呼叫 MQTT 模組的相關功能(由於主題不同,這邊不會多介紹MQTT是甚麼)

Github專案連結: https://github.com/kouke0638/MQTT-HTTPclient-with-FastAPI

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from mqtt_client import *

app = FastAPI() 

# 當路由指向根目錄時,回傳 HTMLResponse 物件 /index.html
@app.get("/")
async def root():
    with open("./page/index.html", "r", encoding="utf-8") as file:
        content = file.read()
    return HTMLResponse(content=content, status_code=200)

# 使用POST方法,用於發送訊息到指定主題,並回傳JSON格式的訊息
# 格式範例: {"server": "test.io", "port": 1883, "topic": "test", "message": "Hello, MQTT!"}
@app.post("/mqtt")
async def mqtt_post(data: dict):
    try:
        # 發送訊息到指定主題
        send_message(data["server"], data["port"], data["topic"], data["message"])
    except Exception as e:
        print(f"Error sending message: {e}")
        return {"error": f"{e}"} # 回傳錯誤訊息
    return {"message": "Message sent successfully"} # 回傳成功訊息

要注意,如果要在Vercel上部屬Python應用程式需要將環境設定為Node.js 18.x 版本避免一些bug

在專案根目錄下,存放vercel.json,用於指定實際執行環境和啟動的檔案

{
  "version": 2,
  "builds": [
      {
          "src": "main.py",
          "use": "@vercel/python"
      }
  ],
  "routes": [
      {"src": "/(.*)", "dest": "/main.py"}
  ]
}

這邊大家可能會注意到,由於服務是冷啟動因此當許久沒有人使用,則該服務反應會比較慢。
如果有興趣,也可以用cloudflare worker撰寫,可能會更快速

使用步驟

可以直接Import現有專案
https://ithelp.ithome.com.tw/upload/images/20241008/20141278U27U1NNpHZ.png
NodeJS版本應該改成18.x 避免 bug
https://ithelp.ithome.com.tw/upload/images/20241008/20141278niK4P3IrHy.png


上一篇
[day-22] - 利用 Github Pages 將 HTML 放上網頁
下一篇
[Day-24] 使用Vercel 環境變數管理你的應用程式
系列文
初學者入門 - 有人叫我寫blog那就來做吧!28
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言