我正在尝试使用 python 函数来执行 .sql 文件。
sql 文件以DROP DATABASE语句开头。
.sql 文件的第一行如下所示:
DROP DATABASE IF EXISTS myDB;
CREATE DATABASE myDB;
Run Code Online (Sandbox Code Playgroud)
.sql 文件的其余部分定义了“myDB”的所有表和视图
蟒蛇代码:
def connect():
conn = psycopg2.connect(dbname='template1', user='user01')
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
cursor = conn.cursor()
sqlfile = open('/path/to/myDB-schema.sql', 'r')
cursor.execute(sqlfile.read())
db = psycopg2.connect(dbname='myDB', user='user01')
cursor = db.cursor()
return db,cursor
Run Code Online (Sandbox Code Playgroud)
当我运行该connect()函数时,我在DROP DATABASE语句中收到错误消息。
错误:
psycopg2.InternalError: DROP DATABASE cannot be executed from a function or multi-command string
Run Code Online (Sandbox Code Playgroud)
我花了很多时间在谷歌上搜索这个错误,但找不到解决方案。
我还尝试在 .sql 文件的顶部添加一个 AUTOCOMMIT 语句,但它没有改变任何东西。
SET AUTOCOMMIT TO ON;
Run Code Online (Sandbox Code Playgroud)
我知道 postgreSQL 不允许您删除当前连接到的数据库,但我不认为这是这里的问题,因为我通过连接到 template1 …
我有一些基于类的视图,
如果表单 POST ,我使用Django 消息框架发送 success_message is_valid。
error_message如果表单 POST 无效,我还想发送自定义。
很明显如何配置success_message,只需使用 SuccessMessageMixin 并添加一个“success_message”变量。我已经为 error_message 尝试了相同的方法,但是我的任何尝试都没有在表单页面上显示错误 Flash 消息 - 我的尝试在下面的else:块中被注释掉了。
向 CBV 发送错误消息似乎是一种非常常见的情况,但我在 Django 文档或在线其他任何地方都找不到任何示例。
有谁知道我怎么能做到这一点?
只是要清楚 - 我不是在谈论添加为特定字段创建的 ValidationErrors。对于工作正常的字段,我有 ValidationErrors。这是指将出现在页面顶部的自定义 Flash 消息。
#views.py
class DocCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
model = Doc
form_class = DocForm
template_name = "doc/doc_form.html"
context_object_name = 'doc'
success_message = 'Doc successfully created!'
error_meesage = "Error saving the Doc, check fields below."
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
def …Run Code Online (Sandbox Code Playgroud) python ×2
django ×1
django-forms ×1
django-views ×1
postgresql ×1
psycopg2 ×1
python-2.7 ×1
sql ×1