简体   繁体   English

使用Flask和Python的Heroku Postgres数据库

[英]Heroku Postgres Database with Flask and Python

Im writing a dummy website for class and I'm having trouble connecting my Heroku Database to my app that's local for now until I push to Heroku. 我正在为课程编写一个虚拟网站,在将Heroku数据库连接到本地应用程序时遇到了麻烦,直到我推送到Heroku。

I'm not sure what the proper way to do this, and I've searched many videos/forums and I can't seem to get a straight answer from them. 我不确定执行此操作的正确方法,并且我搜索了许多视频/论坛,但似乎无法从中获得直接答案。 Ill post some of my code below. 我会在下面张贴我的一些代码。 In dbconnect.py where the insert the heroku database credentials, like the URI, host, etc? 在dbconnect.py中,在何处插入heroku数据库凭据,例如URI,主机等?

#app.py
from flask import Flask, render_template, redirect, url_for, request, session, flash
from functools import wraps


app = Flask(__name__)

app.secret_key = "Gundam"

# login required decorator
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash('You need to login first.')
            return redirect(url_for('login_page'))
    return wrap


@app.route('/')    
def homepage():
    return render_template("main.html")

@app.route('/dashboard/')
@login_required
def dashboard():
    return render_template("dashboard.html")    

@app.errorhandler(404)
def page_not_found(e):
    return render_template("404.html")

@app.route('/login/', methods=["GET", "POST"])    
def login_page():    
    error = ''
    try:
        if request.method == "POST":
            attempted_username = request.form['username']
            attempted_password = request.form['password']

            if attempted_username == "admin" and attempted_password == "password":
                session['logged_in'] = True
                flash('You were just logged in!')
                return redirect(url_for('dashboard'))
            else:
                error = "Invalid Username or Password."    
        return render_template("login.html", error=error)        
    except Exception as e:    
        return render_template("login.html", error=error)

@app.route('/logout/')
def logout():
    session.pop("logged_in", None)        
    return redirect(url_for('homepage'))



if __name__ == '__main__':
    app.run(debug = True)


dbconnect.py

import os
import psycopg2
import urlparse

urlparse.uses_netloc.append("postgres")
url = urlparse.urlparse(os.environ[""])

conn = psycopg2.connect(
    database=url.path[1:],
    user=url.username,
    password=url.password,
    host=url.hostname,
    port=url.port
)

You have to install the postgres database addon in heroku first. 您必须先在heroku中安装postgres数据库插件。 Run the heroku toolbelt in your computer and enter the command heroku addons:create heroku-postgresql:hobby-dev . 在计算机上运行heroku工具带,然后输入命令heroku addons:create heroku-postgresql:hobby-dev Hobby-dev is the free version. Hobby-dev是免费版本。

Once Heroku Postgres has been added a DATABASE_URL setting will be available in the app configuration and will contain the URL used to access the newly provisioned Heroku Postgres service. 添加Heroku Postgres后,应用程序配置中将提供DATABASE_URL设置,并将包含用于访问新配置的Heroku Postgres服务的URL。 Use the value as your database uri. 使用该值作为数据库uri。 The app configuration can be accessed from your dashboard. 可以从仪表板访问应用程序配置。 Under settings, click Reveal config vars . 在设置下,点击Reveal config vars You can also use the toolbelt command. 您也可以使用toolbelt命令。 See heroku config -h . 参见heroku config -h

So now you can do: 现在,您可以执行以下操作:

url = urlparse.urlparse(os.environ["DATABASE_URL"])

For more details see https://devcenter.heroku.com/articles/heroku-postgresql 有关更多详细信息,请参见https://devcenter.heroku.com/articles/heroku-postgresql

Just use the following code snippet on your python app. 只需在您的python应用程序上使用以下代码段即可。 That should do the trick. 这应该够了吧。

import os
import psycopg2


DATABASE_URL = os.environ['DATABASE_URL']
conn = psycopg2.connect(DATABASE_URL, sslmode='require')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM