Logging POST and GET Requests with Flask - python

I am trying to log all activity on my Flask web app using the flask logger. I know how to get logs of application errors as is mentioned in this link
http://flask.pocoo.org/docs/1.0/logging/#logging
The problem with this is that it only returns logs for the first time that i go to the local server to launch the app. No logs are returned after that. Logs are only updated if i change something in my code but not when i log in to the app or go to different tabs within the app. What is the procedure If I want to get the logs for activity within the app?
#app.route("/cis", methods=['GET','POST'])
#login_required
def main():
form = ReusableForm(request.form)
if request.method == 'POST':
if form.validate():
try :
app.logger.info("Reached /cis")
else:
return render_template('cis.html',form=)
For example if i want to show "Reached /cis" in the logs when i visit "/cis" in my app what should be done?

Related

Flask problem when the user looks at the page source code

I have noticed that after a POST, if you look at the page source via "control + U" flask opens the source page also again via POST and does all tasks again. Is there any way I can prevent this?
#app.route("/", methods=["POST", "GET"])
def event_page():
if request.method == "POST":
do_something()
when I view the source page the do_something() function is trigger t again.
Not really a Flask problem. The simplest solutions would be not to use CTRL+U but F12 - inspector or network tab

Flask session log out and redirect to login page

I am using Flask,Python for my web application . The user will login and if the session time is more than 5 minutes then the app should come out and it should land on the login page.
I tried some of the methods and I can see the session time out is happening but redirect to login page is not happening.
#app.before_request
def before_request():
"Session time out method"
flask.session.permanent = True
app.permanent_session_lifetime = datetime.timedelta(minutes=2)
flask.session.modified = True
flask.g.user = flask_login.current_user
#return redirect(url_for('login'))
I have used before_request for seesion time out.
I have referrred this link Flask logout if sessions expires if no activity and redirect for login page
but I dont see any changes from what I have tried before and this code. I can see lot of stackoverflow questions over there for this topic and I couldnt find the solution.
I have tried this link als
Expire session in flask in ajax context
But I am not sure what should I pass as a session and what qualifier I should return here?
#mod.before_request
def make_session_permanent():
if session_is_invalid(session):
return redirect(url_for('logout'))
def session_is_invalid(ses):
# return your qualifier
if the previous method is correct can some one tell me what is the session and what qualifier I should return here?
What I need is after session log out the page should automatically land on the login screen
What is happening is session log out is happening but it's not redirecting to login page
could some one help me in this?
When I read the documents of the Flask-Login package, i saw a few things. When creating your Flask application, you also need to create a login manager.
login_manager = LoginManager()
A login_view variable in LoginManager class caught my attention. The details include the following explanation:
The name of the view to redirect to when the user needs to log in. (This can be an absolute URL as well, if your authentication machinery is external to your application.)
Actually, after you create a LoginManager object,
login_manager.login_view = 'your login view'
You should specify your login page. Finally,
Once the actual application object has been created, you can configure it for login with:
login_manager.init_app(app)
After doing these, any unauthorized calls to every method you use #login_required annotation will be sent to the page you have pointed out with login_view.
I also developed a simple application. You can review this application from here. I tested it and working without any problems.
I hope it helps you.

Why does my session variable clear after closing the browser?

Here is a code snippet that is a simple note application that takes in input from the user and displays the notes on the browser. The notes are stored in the session variable provided by flask. My question is that even though the server is running and the notes I entered are in the variable, why does the notes variable clear when I close the browser?
How can I make it persist even after the browser closes? Please let me know a solution with the use of session variable only.
from flask import Flask, render_template, request, session
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
print(app.config)
notes = []
#app.route("/", methods=["GET", "POST"])
def index():
if session.get("notes") is None:
session["notes"]=[]
if request.method == "POST":
note = request.form.get("note")
session["notes"].append(note)
return render_template("index.html", notes=session["notes"])
Session ID's are generated and stored as a client cookie when the user starts communicating with the server. The sessions themselves are stored in the server (usually in memory, but this is implementation based).
Sessions are meant to be based on single user interaction with a web page. If you don't set a (sufficiently) long expiry for the cookie, it'll wipe the cookie when the browser is exited. Try setting a SET-COOKIE field on the HTTP response timeout.

Flask-login currentuser becomes anonymous after server restart

I successfully completed my web app with Flask ad deployed it on my server. I use current_user in some of my methods and I need that information for some purposes. Lately I noticed a problem. There was already logged in pages and at that point I restarted flask server. Logged in pages were untouched during that. And current_user became anonymous in all open and previously logged in pages. To prevent that, I tried such:
#app.before_request
def make_session_permanent():
session.permanent = True
But still the same problem What should I have done? At least I would like to force all client pages to go to login page after server restart.
with app.secret_key = os.urandom(12)I was using a changing secret key. I did it so that app.secret_key = 'sansal54' and it was solved.

Show processed results in flask to user when he logs in

I'm very new to Flask and don't have much experience in Python.
As required by my project, I need to do certain processing in the backend (through Python script) using the input given by user and show the end results to the user afterwards, whenever he logs in.
A little description as to what my project does - Whenever the user logs in, he/she enters any Twitter handle in html form and the python script gets certain details regarding that handle (number of similar users, followers, no. of tweets, etc.) and this process takes approximately 5-6 minutes. Currently, I am processing and storing all this data in CSVs and then showing the results in HTML.
Now, I don't want my user to wait for those 5-6 minutes to view the results and thus, want the processed results to be stored in the database so that the user can view them whenever he logs in, say even after 1-2 hours.
How should I implement this in Flask, by using SQLAlchemy? I already have made the database for login screen as below, but don't know how to go about this.
from flask import Flask, render_template, session
from sqlalchemy import create_engine
engine = create_engine('sqlite:///tutorial.db', echo=True)
app = Flask(__name__)
#app.route('/')
def home():
if not session.get('logged_in'):
return render_template('login.html')
else:
return render_template('test.html')
#app.route('/login', methods=['POST'])
def do_admin_login():
error = False
POST_USERNAME = str(request.form['username'])
POST_PASSWORD = str(request.form['password'])
Session = sessionmaker(bind=engine)
s = Session()
query = s.query(User).filter(User.username.in_([POST_USERNAME]),
User.password.in_([POST_PASSWORD]))
data = query.first()
if data:
session['logged_in'] = True
flash('Login success')
return render_template('test.html')
else:
flash('Login failed!')
return render_template('login.html',error=True)
#app.route("/logout")
def logout():
session['logged_in'] = False
return home()
The test.html mentioned above takes the twitter handle as input from the user through html form.

Categories

Resources