2017-05-04 6 views
0

私はクラスのためのダミーのウェブサイトを書いています。私はHerokuにプッシュするまで、私のHerokuデータベースを私のアプリに接続するのに問題があります。Herkt Postgres Database with Flask and Python

これを行うにはどのような正しい方法がよくわからず、私は多くのビデオ/フォーラムを検索しましたが、私はそれらからまっすぐ答えを得ることはできません。私のコードは以下の通りです。 dbconnect.pyでは、URI、ホストなどのherokuデータベースクレデンシャルを挿入する場所はどこですか?

#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 
) 

答えて

1

最初にherokuにpostgresデータベースアドオンをインストールする必要があります。コンピュータでherokuの工具ベルトを動かし、heroku addons:create heroku-postgresql:hobby-devというコマンドを入力します。 Hobby-devは無料版です。

Heroku Postgresが追加されると、DATABASE_URL設定がアプリケーション設定で利用可能になり、新たにプロビジョニングされたHeroku PostgresサービスにアクセスするためのURLが含まれます。この値をデータベースのURIとして使用します。アプリの設定は、ダッシュボードからアクセスできます。設定で、Reveal config varsをクリックします。 toolbeltコマンドを使用することもできます。 heroku config -hを参照してください。だから、

今あなたが行うことができます。詳細については

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

https://devcenter.heroku.com/articles/heroku-postgresql

+0

が返事ありがとうござい参照してください。私はすでにすべてをやった。私はちょうどコードが私のアプリにdbをリンクすることであることを理解しているだけです –

+0

'url = urlparse.urlparse(os.environ [" DATABASE_URL "])'を試みましたか?それはheroku環境変数からデータベースのURLを取得する必要があります。 – yovsky