English 中文(简体)
如何将Flask/Peewee与Heroku一起使用?
原标题:How to use Flask/Peewee with Heroku?

我正在尝试部署aFlask应用程序到Heroku。我正在使用Peewe作为Postgres数据库的ORM。当我按照部署Flask的标准Heroku步骤,在我输入Heroku ps:scale web=1后,web进程崩溃。以下是日志内容:

Starting process with command `python app.py`
/app/.heroku/venv/lib/python2.7/site-packages/peewee.py:2434: UserWarning: Table for <class  flask_peewee.auth.User > ("user") is reserved, please override using Meta.db_table
cls, _meta.db_table,
Traceback (most recent call last):
File "app.py", line 167, in <module>
auth.User.create_table(fail_silently=True)
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 2518, in create_table if fail_silently and cls.table_exists():
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 2514, in table_exists return cls._meta.db_table in cls._meta.database.get_tables()
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 507, in get_tables ORDER BY c.relname""")
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 313, in execute cursor = self.get_cursor()
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 310, in get_cursor return self.get_conn().cursor()
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 306, in get_conn self.connect()
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 296, in connect self.__local.conn = self.adapter.connect(self.
database, **self.connect_kwargs)
File "/app/.heroku/venv/lib/python2.7/site-packages/peewee.py", line 199, in connect return psycopg2.connect(database=database, **kwargs)
File "/app/.heroku/venv/lib/python2.7/site-packages/psycopg2/__init__.py", line 179, in connect connection_factory=connection_factory, async=async)
psycopg2.OperationalError: could not connect to server: No such file or directory
Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
Process exited with status 1
State changed from starting to crashed

我尝试了很多不同的方法让Heroku允许我的应用程序与Postgres数据库通信,但都没有成功。有简单的方法吗?我需要做什么来配置Flask/Peewee,以便在Heroku上使用db?

问题回答

根据Peewe docs,除非您的本地数据库驱动程序与远程数据库驱动程序不同(即本地使用SQLite,远程使用Postgres),否则您不想使用Proxy()。但是,如果您在本地和远程都使用Postgress,这是一个更简单的更改。在这种情况下,您只想在运行时更改连接值(数据库名称、用户名、密码、主机、端口等),而不需要使用Proxy()。

Peewee有一个内置的数据库连接url解析器。使用方法如下:

import os
from peewee import *
from playhouse.db_url import connect

db = connect(os.environ.get( DATABASE_URL ))

class BaseModel(Model):
    class Meta:
        database = db

在这个例子中,peewee的db_url模块读取环境变量DATABASE_urlPostgresqlDatabase对象具有这些值。

在本地,您需要将DATABASE_URL设置为环境变量。你可以根据你使用的任何shell的说明来做这件事。或者,如果你想使用Heroku工具链(使用Heroku-local启动本地服务器),你可以添加到项目顶层名为.env的文件中。对于远程设置,您需要将数据库URL添加为远程Heroku环境变量。您可以使用以下命令完成此操作:

heroku config:set DATABASE_URL=postgresql://myurl

您可以通过进入Heroku,导航到您的数据库,然后单击“数据库凭据”来找到该URL。它列在URI下。

您正在解析DATABASE_URL环境变量吗?它看起来像这样:

postgres://username:password@host:port/database_name

因此,在打开与数据库的连接之前,您需要将其拉入并解析。根据您声明数据库的方式(在配置中或wsgi应用程序旁边),它可能看起来像这样:

import os
import urlparse

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

# for your config
DATABASE = {
     engine :  peewee.PostgresqlDatabase ,
     name : url.path[1:],
     password : url.password,
     host : url.hostname,
     port : url.port,
}

请参阅此处的注释:https://devcenter.heroku.com/articles/django一

heroku配置:设置heroku=1

import os
import urlparse
import psycopg2
from flask import Flask
from flask_peewee.db import Database


if  HEROKU  in os.environ:
    DEBUG = False
    urlparse.uses_netloc.append( postgres )
    url = urlparse.urlparse(os.environ[ DATABASE_URL ])
    DATABASE = {
         engine :  peewee.PostgresqlDatabase ,
         name : url.path[1:],
         user : url.username,
         password : url.password,
         host : url.hostname,
         port : url.port,
    }
else:
    DEBUG = True
    DATABASE = {
         engine :  peewee.PostgresqlDatabase ,
         name :  framingappdb ,
         user :  postgres ,
         password :  postgres ,
         host :  localhost ,
         port : 5432 ,
         threadlocals : True
    }

app = Flask(__name__)
app.config.from_object(__name__)
db = Database(app)

Modified coleifer s answer to answer hasenj s comment. Please mark one of these as the accepted answer.

我已经设法让我的Flask应用程序使用Peewee在Heroku上使用以下代码:

# persons.py

import os
from peewee import *

db_proxy = Proxy()

# Define your models here
class Person(Model):
    name = CharField(max_length=20, unique=True)
    age  = IntField()

    class Meta:
        database = db_proxy

# Import modules based on the environment.
# The HEROKU value first needs to be set on Heroku
# either through the web front-end or through the command
# line (if you have Heroku Toolbelt installed, type the following:
# heroku config:set HEROKU=1).
if  HEROKU  in os.environ:
    import urlparse, psycopg2
    urlparse.uses_netloc.append( postgres )
    url = urlparse.urlparse(os.environ["DATABASE_URL"])
    db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port)
    db_proxy.initialize(db)
else:
    db = SqliteDatabase( persons.db )
    db_proxy.initialize(db)

if __name__ ==  __main__ :
    db_proxy.connect()
    db_proxy.create_tables([Person], safe=True)

您应该已经将Postgres数据库附加到您的应用程序中。您可以通过命令行或web前端完成此操作。假设数据库已经连接到您的应用程序,并且您已经部署了应用程序。使用上述更改,登录Heroku并创建表:

$ heroku login
$ heroku run bash
$ python persons.py

检查表是否已创建:

$ heroku pg:psql
your_app_name::DATABASE=> dt 

然后,您将此文件(本例中为persons.py)导入另一个Python脚本中,例如请求处理程序。您需要显式管理数据库连接:

# server.py

from flask import g
from persons import db_proxy

@app.before_request
def before_request():
    g.db = db_proxy
    g.db.connect()

@app.after_request
def after_request(response):
    g.db.close()
    return response

…

参考文献:





相关问题
摘录数据

我如何将Excel板的数据输入我的Django应用? I m将PosgreSQL数据库作为数据库。

Postgres dump of only parts of tables for a dev snapshot

On production our database is a few hundred gigabytes in size. For development and testing, we need to create snapshots of this database that are functionally equivalent, but which are only 10 or 20 ...

How to join attributes in sql select statement?

I want to join few attributes in select statement as one for example select id, (name + + surname + + age) as info from users this doesn t work, how to do it? I m using postgreSQL.

What text encoding to use?

I need to setup my PostgreSQL DB s text encoding to handle non-American English characters that you d find showing up in languages such as German, Spanish, and French. What character encoding should ...

SQL LIKE condition to check for integer?

I am using a set of SQL LIKE conditions to go through the alphabet and list all items beginning with the appropriate letter, e.g. to get all books where the title starts with the letter "A": SELECT * ...