python - 执行查询以从 python flask sqlalchemy 中的文件创建函数时出错
问题描述
我尝试执行 sql 文件以在我的数据库中创建 postgresql 函数。但我有错误。
File "/home/saputra/Documents/Development/Exercises/Python/flask/ujicoba06/smartapps/__init__.py", line 2, in <module>
from smartapps.app import create_app
File "/home/saputra/Documents/Development/Exercises/Python/flask/ujicoba06/smartapps/app.py", line 30, in <module>
from smartapps.commands import func_db
File "/home/saputra/Documents/Development/Exercises/Python/flask/ujicoba06/smartapps/commands/func_db.py", line 18
while current_app.open_resource("commands/func_query.sql") as f:
^
SyntaxError: invalid syntax
我的结构:
.
|-- smartapps
| |-- app.py
| |-- commands
| | |-- func_db.py
| | |-- func_query.sql
| | |-- init_db.py
| | |-- __init__.py
func_query.sql
--function to get staff who don't have user
CREATE OR replace FUNCTION get_staff_not_have_user()
RETURNS TABLE (
real_name varchar,
email varchar
)
AS $$
BEGIN
RETURN query SELECT
st.real_name,
st.email
FROM
public.staff st
LEFT JOIN
public.users us on us.email = st.email
WHERE
us.email IS NULL;
END;
$$ LANGUAGE 'plpgsql';
func_db.py
# -*- coding: utf-8 -*-
import os
import click
from flask import current_app
from flask.cli import with_appcontext
from sqlalchemy.sql import text
from smartapps.extensions import db
def init_func():
"""Clear existing function and create new one"""
while current_app.open_resource("commands/func_query.sql") as f:
db.session.execute(f.read().decode("utf8"))
@click.command("init-func")
@with_appcontext
def func_query_command():
"""Execute sql script"""
init_func()
click.echo('Initialized function for SMART Systems.')
def init_app(app):
app.cli.add_command(func_query_command)
当我从终端运行时,出现错误。如何更正代码以从文件执行查询以在 postgresql 数据库中创建函数。
谢谢
解决方案
语法错误是由于该行中的关键字错误:
while current_app.open_resource("commands/func_query.sql") as f:
第一个词应该with
不是while
。
推荐阅读
- c++ - 如何设置和获取 fipTag 的值
- python - 熊猫在列中找到最大连续下降周数
- java - java可以用小数识别负0吗?
- linux - 如何使用 Ansible 更新远程主机
- django - 如何修复 AttributeError: 'NoneType' 对象没有属性 'id' 和 self.assertEqual(Item.objects.count(), 1) AssertionError: 0 != 1
- javascript - 参数列表后缺少 ),看不到原因吗?
- php - 如何在 PHP 中读取此结果?
- jquery - 当前上下文中不存在 JQuery 变量
- python - 熊猫:保留重复时填写缺失的日期
- seaborn - 由于不推荐使用多维索引的非元组序列,Seaborn 绘制相关图失败