gpt4 book ai didi

python - 在 Flask g 中存储 Postgres 连接

转载 作者:行者123 更新时间:2023-11-29 14:33:17 25 4
gpt4 key购买 nike

我正在尝试使用 Flask g 对象共享单个打开的数据库连接,并在用户登录时保持其打开状态。我遇到的问题是函数 get_db() 看起来像是不使用当前打开的连接,而是每次有新页面请求时打开一个新连接?

如何才能不在每次进入新页面时打开新请求?

数据库文件(qry由其他模块导入):

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import json
import psycopg2
import psycopg2.extras
from flask import g
from urllib import parse

from lingco import app


def load_row(row):
loaded = {}
for k, v in row.items():
loaded[k] = json.loads(v) if type(v) == str else v
return loaded

def connect_db():
parse.uses_netloc.append("postgres")
if "DATABASE_URL" in os.environ:
url = parse.urlparse(os.environ["DATABASE_URL"])
else:
url = parse.urlparse(app.config["DATABASE_URL"])
conn = psycopg2.connect(
database=url.path[1:],
user=url.username,
password=url.password,
host=url.hostname,
port=url.port
)
print("***OPENING CONNECTION***")
return conn


@app.teardown_appcontext
def close_db(error):
"""Closes the database again at the end of the request
if user is not logged in."""
if hasattr(g, 'db_conn') and not hasattr(g, 'user'):
print("***CLOSING CONNECTION***")
g.db_conn.close()
g.pop('db_conn', None)


def get_db():
"""Opens a new database connection if there is none yet for the
current application context.
"""
if not hasattr(g, 'db_conn'):
g.db_conn = connect_db()
return g.db_conn


def qry(query="",args=(),**kwargs):
conn = get_db()
cursor = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
cursor.execute(query,args)
if "commit" in kwargs and kwargs["commit"]==True:
conn.commit()
if "fetch" in kwargs and kwargs["fetch"]=="rowcount":
return cursor.rowcount
if "fetch" in kwargs and kwargs["fetch"]=="all":
records = cursor.fetchall()
if "load"in kwargs and kwargs["load"]==True:
loaded_records = []
for row in records:
loaded_records.append(load_row(row))
return loaded_records
return records
if "fetch" in kwargs and kwargs["fetch"]=="one":
record = cursor.fetchone()
if "load"in kwargs and kwargs["load"]==True:
record = load_row(record)
if "attr" in kwargs:
return record[kwargs["attr"]]
return record

终端输出:

host-162571:flask_try sethkillian$ python run.py
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 692-579-362
127.0.0.1 - - [25/Jan/2018 16:28:51] "GET /login HTTP/1.1" 200 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:01] "POST /login HTTP/1.1" 302 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:01] "GET /dashboard/ HTTP/1.1" 200 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:07] "GET /dashboard/2/roster HTTP/1.1" 200 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:13] "GET /dashboard/ HTTP/1.1" 200 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:18] "GET /questions HTTP/1.1" 200 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:20] "GET /static/js/question_database.js HTTP/1.1" 200 -
***OPENING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:34] "GET / HTTP/1.1" 200 -
***OPENING CONNECTION***
***CLOSING CONNECTION***
127.0.0.1 - - [25/Jan/2018 16:29:39] "GET /logout HTTP/1.1" 302 -
127.0.0.1 - - [25/Jan/2018 16:29:39] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [25/Jan/2018 16:29:43] "GET /dashboard/ HTTP/1.1" 302 -
127.0.0.1 - - [25/Jan/2018 16:29:43] "GET /login HTTP/1.1" 200 -

最佳答案

g 对象仅对当前请求上下文是全局的。这意味着当同一用户发送新请求时,新请求有自己的 g 对象。

一种拥有全局连接对象的解决方案:如果您想确保只有一个连接对象,只需使用普通的全局对象和一些簿记即可。

conn = None

def get_db():
global conn
if conn is None:
conn = connect_db()
return conn

关于python - 在 Flask g 中存储 Postgres 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com