기본 콘텐츠로 건너뛰기

Flask 11. 로그인 페이지 만들기

Flask 11. 로그인 페이지 만들기

먼저 세션과 쿠키의 개념을 알아야한다.

쿠키란?

쿠키는 클라이언트(브라우저) 로컬에 저장되는 키와 값이 들어있는 데이터파일이다.

사용자 인증이 유효한 시간을 명시할 수 있으며, 유효 시간이 정해지면 브라우저가 종료되어도 인증이 유지된다는 특징이 있다.

세션이란?

세션은 쿠키를 기반하고 있지만, 사용자 정보 파일을 브라우저에 저장하는 쿠키와 달리 세션은 서버 측에서 관리한다.

서버에서는 클라이언트를 구분하기 위해 세션 ID를 부여하며 웹 브라우저가 서버에 접속해서 브라우저를 종료할 때까지 인증상태를 유지한다.

이로써, 로그인을 구현하기 위해서는 세션이 필요하다. flask에 session 모듈을 import한다.

1. View - login.html

클라이언트에서 요청했을 때 보여줘야 하는 페이지를 register.html을 기반으로 생성한다. body부분을 제외하고 동일하므로 body부분만 적겠다.

... 로그인 {{form.csrf_token}} {{form.userid.label("아이디")}} {{form.userid(class="form-control", placeholder="아이디")}} {{form.password.label("비밀번호")}} {%if form.password.errors%} {{form.password.errors.0}} {%endif%} {{form.password(class="form-control", placeholder="비밀번호")}} 로그인 ...

2. Control - app.py

/login으로 들어왔을 때 처리해야하는 비즈니스 로직을 작성해보자.

from flask import session ... @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): print('{}가 로그인 했습니다.'.format(form.data.get('userid'))) ssession['userid'] = form.data.get('userid') return redirect('/') return render_template('login.html', form=form) ...

session 변수에 값만 저장해주면 알아서 클라이언트가 구분되고, 세션정보 또한 사용할 수 있다. 굉장히 편하게 세션을 관리할 수 있다.

3. form 생성

유효성을 검사하기 위해서 wtf 패키지를 이용할 form을 생성한다.

class LoginForm(FlaskForm): class UserPassword(object): def __init__(self, message=None): self.message = message def __call__(self, form, field): userid = form['userid'].data password = field.data fcuser = Fcuser.query.filter_by(userid=userid).first() if fcuser.password != password: raise ValueError('Wrong Password!') userid = StringField('userid', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired(), UserPassword()])

아이디 : asdf1234

비밀번호 : asdf

비밀번호를 잘못입력함 로그인 성공 시 userid가 나온다.

from http://ohdowon064.tistory.com/119 by ccl(A) rewrite - 2020-03-11 15:20:09

댓글

이 블로그의 인기 게시물

Dummy to resolve the flask problems

Dummy to resolve the flask problems This post is about flask problems that I struggled with. Hope you this is useful things when you taste it. Issue : How to deploy a flask application on Apache2 Resolve : As you know, flask is a micro framework. It can be handled on Apache2 using WSGI module. See the reference. Reference: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps Issue : Flask caused ERR_CONNECTION_ABORTED on POST Resolve : There are lots issues for this problem in principle. It caused when browser keep sending some buffer but server doesn't want to receive. My case is like this (submit.html) (submit.py) @bp.route('/submit', methods=["GET", "POST"]) def submit(): return render_template("submit.html") This kinda skel code to explain this. In flask case, this can be caused when it runs as develop server such as run...

외래어 정리

외래어 정리 [A] acacia 아카시아 academic 아카데믹 academy 아카데미 acanthus 아칸서스 accelerator 액셀러레이터 accent 악센트 acceptor 억셉터 access 액세스 accessory 액세서리 accordion 아코디언 ace 에이스 acetate 아세테이트 acetaldehyde 아세트알데히드 acetic acid 아세트(산) acetone 아세톤 acetyl 아세틸 acetylene 아세틸렌 Achilles tendon 아킬레스(건) acre 에이커 acrylic acid 아크릴(산) action 액션 active 액티브 acyl 아실 AD 에이디 adagio 아다지오 adapter 어댑터 ad + balloon 애드벌룬 address 어드레스 adenine 아데닌 adrenaline 아드레날린 advantage 어드밴티지 aerobic dance 에어로빅 댄스 aerofoil 에어로포일 aerosol 에어로졸 afghan 아프간 [편물] after + service 애프터서비스 agape 아가페 Ainu 아이누 air conditioner 에어컨(디셔너) airspray 에어스프레이 album 앨범 albumin 알부민 alcohol 알코올 aldehyde 알데히드 ALGOL 알골 algorism 알고리즘 alibi 알리바이 alkali 알칼리 alkaloid 알칼로이드 Allah 알라 allegory 알레고리 allegretto 알레그레토 allegro 알레그로 alleluia 알렐루야 Allergie 알레르기 alligator 앨리게이터 all-in-one 올인원 almond 아몬드 aloha 'oe 알로하 오에 Alpenhorn 알펜호른 alpha 알파 alphabet 알파벳 ...

스프링 프레임워크(Spring Framework)란?

스프링 프레임워크(Spring Framework)란? "코드로 배우느 스프링 웹 프로젝트"책을 개인 공부 후 자료를 남기기 위한 목적이기에 내용 상에 오류가 있을 수 있습니다. '스프링 프레임워크'가 무엇인지 말 할 수 있고, 해당 프레임워크의 특징 및 장단점을 설명할 수 잇는 것을 목표로합니다. 1. 프레임워크란? 2. 스프링 프레임워크 "뼈대나 근간을 이루는 코드들의 묶음" Spring(Java의 웹 프레임워크), Django(Python의 웹 프레임워크), Flask(Python의 마이크로 웹 프레임워크), Ruby on rails(Ruby의 웹 프레임워크), .NET Framework, Node.js(Express.js 프레임워크) 등등. 프레임워 워크 종류 : 3. 개발 시간을 단축할 수 있다. 2. 일정한 품질이 보장된 결과물을 얻을 수 있다. 1. 실력이 부족한 개발자라 허다러도 반쯤 완성한 상태에서 필요한 부분을 조립하는 형태의 개발이 가능하다. 프레임워크를 사용하면 크게 다음 3가지의 장점 이 있습니다. 프레임워크 이용 한다는 의미 : 프로그램의 기본 흐름이나 구조를 정하고, 모든 팀원이 이 구조에 자신의 코드를 추가하는 방식으로 개발 한다. => 이러한 상황을 극복하기 위한 코드의 결과물이 '프레임워크' 입니다. 개발자는 각 개개인의 능력차이가 크고, 따라서 개발자 구성에 따라서 프로젝트의 결과 차이가 큽니다. 2. 스프링 프레임워크(Spring Framework) 자바 플랫폼을 위한 오픈 소스 애플리케이션 스프링의 다른 프레임워크와 가장 큰 차이점은 다른 프레임워크들의 포용 입니다. 이는 다시말해 기본 뼈대를 흔들지 않고, 여러 종류의 프레임워크를 혼용해서 사용할 수 있다는 점입니다. 대한민국 공공기관의 웹 서비스 개발 시 사용을 권장하고 있는 전자정부 표준프레임워크 이다. 여러 프레임워크들 중 자바(JAV...