1
0
forked from ScoDoc/ScoDoc

connexion bd dept avec Flask global. Testé en mode DEBIG seulement.

This commit is contained in:
Emmanuel Viennet 2021-06-25 18:25:46 +02:00
parent 692a8fabd5
commit 8d62455ef0
10 changed files with 81 additions and 24 deletions

View File

@ -7,6 +7,8 @@ from logging.handlers import SMTPHandler, RotatingFileHandler
from flask import request from flask import request
from flask import Flask from flask import Flask
from flask import current_app
from flask import g
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate from flask_migrate import Migrate
from flask_login import LoginManager from flask_login import LoginManager
@ -16,6 +18,8 @@ from flask_moment import Moment
from config import Config from config import Config
from app.scodoc import notesdb as ndb
app = Flask(__name__) app = Flask(__name__)
app.config.from_object(Config) app.config.from_object(Config)
@ -29,6 +33,20 @@ bootstrap = Bootstrap(app)
moment = Moment() moment = Moment()
@app.before_request
def open_dept_db_connection():
# current_app.logger.info("open_dept_db_connection")
if hasattr(g, "scodoc_dept") and not hasattr(g, "db_conn"):
g.db_conn = ndb.open_dept_connection()
@app.teardown_request
def close_dept_db_connection():
# current_app.logger.info("close_dept_db_connection")
if hasattr(g, "db_conn"):
ndb.close_dept_connection()
def create_app(config_class=Config): def create_app(config_class=Config):
app = Flask(__name__, static_url_path="/ScoDoc/static", static_folder="static") app = Flask(__name__, static_url_path="/ScoDoc/static", static_folder="static")
app.logger.setLevel(logging.DEBUG) app.logger.setLevel(logging.DEBUG)

View File

@ -16,6 +16,8 @@ from flask import request
from flask_login import current_user from flask_login import current_user
from flask_login import login_required from flask_login import login_required
from flask import current_app from flask import current_app
import app
from app.auth.models import Permission from app.auth.models import Permission
@ -144,6 +146,8 @@ def scodoc7func(context):
del kwargs["scodoc_dept"] del kwargs["scodoc_dept"]
elif not hasattr(g, "scodoc_dept"): elif not hasattr(g, "scodoc_dept"):
g.scodoc_dept = None g.scodoc_dept = None
# --- Open DB connection
app.open_dept_db_connection()
# --- Emulate Zope's REQUEST # --- Emulate Zope's REQUEST
REQUEST = ZRequest() REQUEST = ZRequest()
g.zrequest = REQUEST g.zrequest = REQUEST

View File

@ -8,6 +8,8 @@ import psycopg2.pool
import psycopg2.extras import psycopg2.extras
import thread import thread
from flask import g
import app.scodoc.sco_utils as scu import app.scodoc.sco_utils as scu
from app.scodoc.notes_log import log from app.scodoc.notes_log import log
from app.scodoc.sco_exceptions import ScoException, ScoValueError, NoteProcessError from app.scodoc.sco_exceptions import ScoException, ScoValueError, NoteProcessError
@ -38,21 +40,39 @@ def unquote(s):
# pour l'instance donnee par context # pour l'instance donnee par context
# La connexion est unique (réutilisée) pour chaque thread # La connexion est unique (réutilisée) pour chaque thread
# et est par défaut en autocommit # et est par défaut en autocommit
_pools = {} # _pools = {}
#
#
# def GetDBConnexion(autocommit=True):
# """connexion to the DB of a departement"""
# pool = _pools.get(scu.get_db_cnx_string(), None)
# if not pool:
# pool = psycopg2.pool.ThreadedConnectionPool(2, 8, dsn=scu.get_db_cnx_string())
# _pools[scu.get_db_cnx_string()] = pool
# # log('GetDBConnexion: created pool for "%s"' % scu.get_db_cnx_string())
# cnx = pool.getconn(key=(thread.get_ident(), autocommit))
# # log('GetDBConnexion: autocommit=%s cnx=%s' % (autocommit,cnx))
# if cnx.autocommit != autocommit:
# cnx.autocommit = autocommit
# return cnx
def GetDBConnexion(autocommit=True): def open_dept_connection():
"""connexion to the DB of a departement""" """Open a connection to the current dept db"""
pool = _pools.get(scu.get_db_cnx_string(), None) # log("open_dept_connection to " + scu.get_db_cnx_string()) # XXX
if not pool: return psycopg2.connect(scu.get_db_cnx_string())
pool = psycopg2.pool.ThreadedConnectionPool(2, 8, dsn=scu.get_db_cnx_string())
_pools[scu.get_db_cnx_string()] = pool
# log('GetDBConnexion: created pool for "%s"' % scu.get_db_cnx_string()) def close_dept_connection():
cnx = pool.getconn(key=(thread.get_ident(), autocommit)) """Commit and close dept db."""
# log('GetDBConnexion: autocommit=%s cnx=%s' % (autocommit,cnx)) # log("close_dept_connection to " + scu.get_db_cnx_string()) # XXX
if cnx.autocommit != autocommit: g.db_conn.commit()
cnx.autocommit = autocommit g.db_conn.close()
return cnx
# Essai bien plus simple pour Flask:
def GetDBConnexion(autocommit=True): # on n'utilise plus autocommit
return g.db_conn
# Same for users: # Same for users:

View File

@ -32,6 +32,7 @@
import string import string
import time import time
import types
import datetime import datetime
import calendar import calendar
import cgi import cgi
@ -60,7 +61,8 @@ def _isFarFutur(jour):
def _toboolean(x): def _toboolean(x):
"convert a value to boolean" "convert a value to boolean"
return x # not necessary anymore ! assert (x is None) or isinstance(x, types.IntType) # sco8
return bool(x)
def is_work_saturday(context): def is_work_saturday(context):
@ -316,7 +318,13 @@ WHERE A.ETUDID = %(etudid)s
+ """ + """
AND A.JOUR BETWEEN %(debut)s AND %(fin)s AND A.JOUR BETWEEN %(debut)s AND %(fin)s
""", """,
{"etudid": etudid, "debut": debut, "fin": fin, "moduleimpl_id": moduleimpl_id}, {
"etudid": etudid,
"debut": debut,
"fin": fin,
"matin": matin,
"moduleimpl_id": moduleimpl_id,
},
) )
res = cursor.dictfetchall() res = cursor.dictfetchall()
return res return res

View File

@ -28,7 +28,7 @@ function ajaxFunction(mod, etudid, dat) {
document.getElementById("AjaxDiv").innerHTML = ajaxRequest.responseText; document.getElementById("AjaxDiv").innerHTML = ajaxRequest.responseText;
} }
} }
ajaxRequest.open("POST", SCO_URL + "Absences/doSignaleAbsenceGrSemestre", true); ajaxRequest.open("POST", SCO_URL + "/Absences/doSignaleAbsenceGrSemestre", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var oSelectOne = $("#abs_form")[0].elements["moduleimpl_id"]; var oSelectOne = $("#abs_form")[0].elements["moduleimpl_id"];
var index = oSelectOne.selectedIndex; var index = oSelectOne.selectedIndex;

View File

@ -15,7 +15,7 @@ function display_itemsuivis(active) {
if (!readonly) { if (!readonly) {
$('#adddebouchelink').off("click").click(function (e) { $('#adddebouchelink').off("click").click(function (e) {
e.preventDefault(); e.preventDefault();
$.post(SCO_URL + "itemsuivi_create", { etudid: etudid, format: 'json' }).done(item_insert_new); $.post(SCO_URL + "/itemsuivi_create", { etudid: etudid, format: 'json' }).done(item_insert_new);
return false; return false;
}); });

View File

@ -19,7 +19,7 @@ function loadGroupes() {
$("#gmsg")[0].innerHTML = 'Chargement des groupes en cours...'; $("#gmsg")[0].innerHTML = 'Chargement des groupes en cours...';
var partition_id = document.formGroup.partition_id.value; var partition_id = document.formGroup.partition_id.value;
$.get(SCO_URL + 'XMLgetGroupsInPartition', { partition_id: partition_id }) $.get(SCO_URL + '/XMLgetGroupsInPartition', { partition_id: partition_id })
.done( .done(
function (data) { function (data) {
var nodes = data.getElementsByTagName('group'); var nodes = data.getElementsByTagName('group');

View File

@ -41,7 +41,7 @@ function save_note(elem, v, etudid) {
var evaluation_id = $("#formnotes_evaluation_id").attr("value"); var evaluation_id = $("#formnotes_evaluation_id").attr("value");
var formsemestre_id = $("#formnotes_formsemestre_id").attr("value"); var formsemestre_id = $("#formnotes_formsemestre_id").attr("value");
$('#sco_msg').html("en cours...").show(); $('#sco_msg').html("en cours...").show();
$.post(SCO_URL + 'Notes/save_note', $.post(SCO_URL + '/Notes/save_note',
{ {
'etudid': etudid, 'etudid': etudid,
'evaluation_id': evaluation_id, 'evaluation_id': evaluation_id,

View File

@ -132,12 +132,14 @@ import app.scodoc.VERSION as VERSION
context = ScoDoc7Context("notes") context = ScoDoc7Context("notes")
def sco_publish(route, function, permission): def sco_publish(route, function, permission, methods=["GET"]):
"""Declare a route for a python function, """Declare a route for a python function,
protected by permission and called following ScoDoc 7 Zope standards. protected by permission and called following ScoDoc 7 Zope standards.
""" """
# f = # f =
bp.route(route)(permission_required(permission)(scodoc7func(context)(function))) bp.route(route, methods=methods)(
permission_required(permission)(scodoc7func(context)(function))
)
# setattr(sys.modules[__name__], f.__name__, f) # setattr(sys.modules[__name__], f.__name__, f)
@ -1563,7 +1565,12 @@ sco_publish(
Permission.ScoEnsView, Permission.ScoEnsView,
) )
sco_publish("/saisie_notes", sco_saisie_notes.saisie_notes, Permission.ScoEnsView) sco_publish("/saisie_notes", sco_saisie_notes.saisie_notes, Permission.ScoEnsView)
sco_publish("/save_note", sco_saisie_notes.save_note, Permission.ScoEnsView) sco_publish(
"/save_note",
sco_saisie_notes.save_note,
Permission.ScoEnsView,
methods=["GET", "POST"],
)
sco_publish( sco_publish(
"/do_evaluation_set_missing", "/do_evaluation_set_missing",
sco_saisie_notes.do_evaluation_set_missing, sco_saisie_notes.do_evaluation_set_missing,

View File

@ -1011,7 +1011,7 @@ def _do_cancel_dem_or_def(
return REQUEST.RESPONSE.redirect("ficheEtud?etudid=%s" % etudid) return REQUEST.RESPONSE.redirect("ficheEtud?etudid=%s" % etudid)
@bp.route("/etudident_create_form") @bp.route("/etudident_create_form", methods=["GET", "POST"])
@permission_required(Permission.ScoEtudInscrit) @permission_required(Permission.ScoEtudInscrit)
@scodoc7func(context) @scodoc7func(context)
def etudident_create_form(context, REQUEST=None): def etudident_create_form(context, REQUEST=None):
@ -1019,7 +1019,7 @@ def etudident_create_form(context, REQUEST=None):
return _etudident_create_or_edit_form(context, REQUEST, edit=False) return _etudident_create_or_edit_form(context, REQUEST, edit=False)
@bp.route("/etudident_edit_form") @bp.route("/etudident_edit_form", methods=["GET", "POST"])
@permission_required(Permission.ScoEtudInscrit) @permission_required(Permission.ScoEtudInscrit)
@scodoc7func(context) @scodoc7func(context)
def etudident_edit_form(context, REQUEST=None): def etudident_edit_form(context, REQUEST=None):