我在 Vercel 上部署了 Flask 应用程序。
但我找不到任何有关如何将 PostgreSQL 数据库连接到 Vercel 上的应用程序的 StakOverflow 答案或 YouTube 教程。
我正在阅读文档,但似乎这只适用于 Node.js 应用程序。 我们可以在 VERCEL 上部署 Flask 应用程序吗? 这是我完整的 github 存储库
https://github.com/ELentiya-001/Blog_Website
如何将创建的SQLite数据库连接到应用程序
使用 SQLAlchemy 将 Flask 连接到 Vercel 的 PostgreSQL 非常简单。 Vercel 的 PostgreSQL 使用 Neon DB,因此设置是相同的,您只需要一个连接字符串和 SQLAlchemy。
转到项目设置并复制不带
psql
的连接字符串
这是一个简单的演示:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
# Initialize Flask app and set connection string from Vercel's dashboard
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "<paste_your_postgresql_connection_string_here>"
# Initialize SQLAlchemy and defining a simple Book model
db = SQLAlchemy(app)
class Book(db.Model):
book_id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
# Create database tables in the PostgreSQL database
with app.app_context():
db.create_all()
if __name__ == "__main__":
app.run(debug=True)
还有一件事,要避免 SQL Alchemy 方言错误,如这个 stackoverflow 问题
URI 应以
postgresql://
开头,而不是 postgres://
。
SQLAlchemy 过去接受两者,但删除了对 postgres
名称的支持。 #第一个答案有效。
还考虑使用环境变量来确保应用程序安全。
请参阅此文档来设置无服务器 postgresql: