I am developing a web application that needs to login to the database with credentials that are provided by the end user; the application itself does not have a login to the database.
The problem is how to create one connection per user session.
One approach is:
- Request user's credentials
- Check if credentials are valid against db backend
- Store credentials in session-level variable
Problem with this approach is, on each subsequent request for that session; you would need to create a new connection; and this will quickly exhaust the max connections to the server.
I am using Flask with Oracle.
In Flask, there is a g
object, which stores request-scoped objects. This snippet though, does not work:
app = Flask(__name__)
app.config.from_object(__name__)
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.db is None:
return redirect(url_for('login', next=request.url))
return f(*args, **kwargs)
return decorated_function
class LoginForm(Form):
username = TextField('Username', [validators.Length(min=4, max=25)])
password = PasswordField('Password', [validators.Required()])
@app.route('/app', methods=['GET','POST'])
@login_required
def index():
return 'Index'
@app.route('/', methods=['GET','POST'])
def login():
form = LoginForm(request.form)
if request.method == 'POST':
if form.validate():
try:
dsn = cx_Oracle.makedsn(app.config['DB_HOST'],
app.config['DB_PORT'], app.config['DB_SID'])
g.db = cx_Oracle.connect(form.username.data,
form.password.data, dsn)
except cx_Oracle.DatabaseError as e:
flash(unicode(e), 'error')
return render_template('login.html', form=form)
return redirect(url_for('index'))
else:
return render_template('login.html', form=form)
else:
return render_template('login.html', form=form)
AttributeError: '_RequestGlobals' object has no attribute 'db'