无法在视图函数外使用会话变量

时间:2016-12-10 22:35:40

标签: flask

我有登录页面,用户输入用户名和密码。我已经在/ login视图函数中将用户名作为会话变量,并希望在if-else块中的代码主体中的view函数之外使用此变量。

session['username'] = request.form['username'].lower()

我该怎么做?

以下是此代码的一部分:

import os
import csv
import pymysql
import pymysql.cursors
from datetime import date
import calendar
import ssl
from ldap3 import Connection, Server, ANONYMOUS, SIMPLE, SYNC, ASYNC,ALL
from flask import Flask, make_response,render_template,url_for,redirect,request,session,escape
from validusers import users

app = Flask(__name__)
IT = pymysql.connect(host='xx.xx.xx.xx', user='xxxxx', password='xxxxx',
             db='xxxx')#Connect  to the IT database
Others = pymysql.connect(host='xxxxx', user='xxxxxx', password='xxxxxx',
             db='xxxxx')#Connect to the non IT database
a=IT.cursor() # Open Cursor for IT  database
b=Others.cursor()#Open Cursor for non-IT  database
**@app.route('/')
@app.route('/login',methods=['GET', 'POST'])
def login():
    error=None
    if request.method =='POST':

        #if not request.form['username']:
            #error='You  forgot to enter "Username", please  try again'
            #return render_template('login.html',error=error)
        if request.form['username'].lower() not in users:
            error='You are not authorized to view this page !!'
            return render_template('login.html',error=error)

        #if not request.form['password']:
            #error='You  forgot to enter "Password", please  try again'
            #return render_template('login.html',error=error)
        #else:
            #s = Server('appauth.corp.domain.com:636', use_ssl=True, get_info=ALL)
            #c = Connection(s,user=request.form['username'],password=request.form['password'],check_names=True, lazy=False,raise_exceptions=False)
            #c.open()
            #c.bind()
            #if (c.bind() != True) is True:
                #error='Invalid credentials. Please try again'
            #else:
                #session['username'] = request.form['username'].lower()
                #return redirect(url_for('index'))

    return render_template('login.html',error=error)**



@app.route('/index',methods=['GET','POST'])
def index():
    if 'username' in session:
        return render_template('index.html')



Filename = os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop\RosterUnified.csv" # Create/write  a CSV file  in the  user's desktop
Filename1=os.getenv("HOMEDRIVE") + os.getenv("HOMEPATH") + "\\Desktop\RosterCurrentMonth.csv"
d=open(Filename, 'w',newline='\n') #Format for CSV  input
c = csv.writer(d)
c.writerow(["Manager NT ID"," Vertical Org","Employee ID" ]+ dayssl)# Write  the  header list of strings  in the  first row
for row in result_IT:
    c.writerow(row)#Write output for IT to csv
d.close()

#result_IT  and result_Oters  part  of code   is ommitted
e=open(Filename, 'a',newline='\n')

f= csv.writer(e)
for row in result_Others:
    f.writerow(row)# Append to the  existing  CSV file with non IT data 
e.close()

x=session['username']
sql="select verticalorg from tbl_employeedetails where empntid=(%s)"
args=x
a.execute(sql,args)
b.execute(sql,args)
c=a.fetchall()
d1=b.fetchall()
s=c+d1
q=[x[0]  for x in s]
sql1="select role from tbl_employeedetails where empntid=(%s)"
a.execute(sql1,args)
b.execute(sql1,args)
c1=a.fetchall()
d2=b.fetchall()
Role=c1+d2
r=[x[0]  for x in Role]
if r=='O':
    if q==27:
        f1=open(Filename,'r',newline='\n')
        f2=open(Filename1,'w',newline='\n')
        reader = csv.DictReader(f1)
        writer = csv.writer(f2)
        writer.writerow(["Manager NT ID"," Vertical Org","Employee ID" ]+ dayssl)
        rows = [row for row in reader if row['Vertical Org'] == 'HR']
        writer.writerow[row in rows]
    elif q==2:
        f1=open(Filename,'r',newline='\n')
        f2=open(Filename1,'w',newline='\n')
        reader = csv.DictReader(f1)
        writer = csv.writer(f2)
        writer.writerow(["Manager NT ID"," Vertical Org","Employee ID" ]+ dayssl)

    f2.close()
    z=open(Filename1)
    with z as f:
        p = f.read()

else:
    z=open(Filename)
    with z as f:
        p = f.read()

@app.route('/csv/')  
def download_csv(): 
    csv = p
    response = make_response(csv)
    cd = 'attachment; filename=RosterCurrentMonth.csv'
    response.headers['Content-Disposition'] = cd 
    response.mimetype='text/csv'

    return response
z.close()
os.remove(Filename)
@app.route('/logout')
def logout():
    # remove the username from the session if it's there
    session.pop('username', None)
    return redirect(url_for('login'))
app.secret_key ='secret key generated'
if __name__=='__main__':
    context=('RosterWeb.crt','RosterWeb.key')
    app.run(ssl_context=context, threaded=True, debug=True)

得到错误:

Traceback (most recent call last):
  File "roster.py", line 175, in <module>
    x=session['username']
  File "C:\Users\dasa17\Envs\r_web\lib\site-packages\werkzeug\local.py", line 37
3, in <lambda>
    __getitem__ = lambda x, i: x._get_current_object()[i]
  File "C:\Users\dasa17\Envs\r_web\lib\site-packages\werkzeug\local.py", line 30
2, in _get_current_object
    return self.__local()
  File "C:\Users\dasa17\Envs\r_web\lib\site-packages\flask\globals.py", line 37,
 in _lookup_req_object
    raise RuntimeError(_request_ctx_err_msg)
RuntimeError: Working outside of request context.

This typically means that you attempted to use functionality that needed
an active HTTP request.  Consult the documentation on testing for
information about how to avoid this problem.

1 个答案:

答案 0 :(得分:0)

在函数中完成任何路由之前,您需要放置要运行的代码,并在其上使用before_first_request decorator。它将在您的第一个请求完成之前执行,您可以从那里使用您的会话变量。

@app.route('/')
def index():
    # ... index route here ...
    pass

@app.before_first_request
def init_app():
    # ... do some preparation here ...
    session['username'] = 'me'