Development/Flask with Python
[Flask1.1][Mysql] 실습 - 6 : 로그인시 접속한 기기의 IP 정보 받기 & 로그인 페이지 리다이렉트 기능 추가
Best Junior
2020. 1. 6. 01:44
[ 작업환경 ]
Centos 7.7
Flask 1.1
Python 3.7
로그인 시 접속한 기기의 IP 정보를 저장하는 기능과
로그인된 상태에서 login 페이지 접근시 redirect하는 기능 추가
1. 접속한 기기의 IP 정보 저장 함수 생성
# vim app001/models.py
# ...
def update_fromip(fromip, id):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('UPDATE `pythondb`.`accounts` SET `fromip`=%s WHERE `id`=%s', (fromip, str(id)))
mysql.connection.commit()
2. 접속 기기의 IP 받아 저장하기
로그인 성공시, User.update_fromip 함수를 활용해 ip 정보를 DB에 저장
# vim app001/routes.py
# ...
# http://host:5005/login/ - this will be the login page, we need to use both GET and POST requests
@app.route('/login/', methods=['GET', 'POST'])
def login():
# ...
if account:
session['loggedin'] = True
session['id'] = account['id']
session['username'] = account['username']
#return 'Logged in successfully!'
fromip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
User.update_fromip(fromip, account['id'])
return redirect(url_for('home'))
else:
msg = 'Incorrect username/password!'
# Show the login form with message (if any)
return render_template('index.html', msg=msg)
참고 링크 : https://growingsaja.tistory.com/319
3. 로그인된 상태일 경우 login페이지 접근시 home으로 리다이렉트 기능 추가
# vim app001/routes.py
# ...
# ...
else:
msg = 'Incorrect username/password!'
if 'loggedin' in session:
return redirect(url_for('home'))
# Show the login form with message (if any)
return render_template('index.html', msg=msg)