땅지원
땅지원's Personal blog
땅지원
전체 방문자
오늘
어제
  • 전체 (353)
    • Frontend (2)
      • React (2)
    • Backend (90)
      • Java (16)
      • Python (19)
      • Spring (23)
      • Database (21)
      • Troubleshooting (8)
    • DevOps (27)
      • ELK (13)
    • CS (40)
    • OS (2)
      • Linux (2)
    • Algorithm (95)
      • concept (18)
      • Algorithm Problem (77)
    • 인공지능 (25)
      • 인공지능 (12)
      • 연구노트 (13)
    • 수업정리 (35)
      • 임베디드 시스템 (10)
      • 데이터통신 (17)
      • Linux (8)
    • 한국정보통신학회 (5)
      • 학술대회 (4)
      • 논문지 (1)
    • 수상기록 (8)
      • 수상기록 (6)
      • 특허 (2)
    • 삼성 청년 SW 아카데미 (6)
    • 42seoul (12)
    • Toy project (3)
    • 땅's 낙서장 (2)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

  • 20.11.6 BB21플러스 온라인 학술대회
  • 20.10.30 한국정보통신학회 온라인 학술대회

인기 글

태그

  • I
  • D
  • 이것이 리눅스다 with Rocky Linux9
  • ㅗ
  • E

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
땅지원

땅지원's Personal blog

Backend/Python

Python Flask + mysql 웹 기반 어플리케이션 제작

2021. 11. 27. 19:51

Directory

project

└static

    └style.css

    └ ...

└templates

    └index.html

    └login.html

    └ ...
└run.py

 

#run.py


# Import Flask Library
from flask import Flask, render_template, request, session, url_for, redirect
import pymysql.cursors

# Initialize the app from Flask
app = Flask(__name__)

# Configure MySQL
conn = pymysql.connect(host='localhost',
                       user='root',
                       password='1234',
                       db='travel',
                       charset='utf8mb4',
                       cursorclass=pymysql.cursors.DictCursor)


# Define a route to hello function
@app.route('/')
def hello():
    return render_template('index.html')

# Authenticates the login
@app.route('/loginAuth', methods=['GET', 'POST'])
def loginAuth():
    # grabs information from the forms
    username = request.form['username']
    password = request.form['password']
    kindoflogin = request.form['kind']
    print(kindoflogin)
    # cursor used to send queries
    cursor = conn.cursor()
    query =''
    # executes query


    if kindoflogin == 'customer':
        query = 'SELECT * FROM customer WHERE email = %s and password = md5(%s)'
    elif kindoflogin == 'works':
        query = 'SELECT * FROM airline_staff WHERE username = %s and password = md5(%s)'

    print(query)
    cursor.execute(query, (username, password))
    # stores the results in a variable
    data = cursor.fetchone()
    # use fetchall() if you are expecting more than 1 data row
    cursor.close()
    error = None
    if (data):
        # creates a session for the the user
        # session is a built in
        session['username'] = username
        return redirect(url_for('home'))
    else:
        # returns an error message to the html page
        error = 'Invalid login or username'
        return render_template('login.html', error=error)


@app.route('/logout')
def logout():
    session.pop('username')
    return redirect('/')


# Run the app on localhost port 5000
# debug = True -> you don't have to restart flask
# for changes to go through, TURN OFF FOR PRODUCTION
if __name__ == "__main__":
    app.run('127.0.0.1', 5000, debug=True)

retrun render_template에 html 제외한 인자가 하나 더 있으면 html파일 내에서  {{value}}이렇게 표시해서 나타낸다.

request.form은 form의 name을 이용하여 짝을 지어 py내에서 값을 받아올 수 있다.

<!-- vim /templates/index.html -->

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Login</title>

	</head>
	<body>
			<h1>Login</h1>

			<div class="links">
				<a href="{{ url_for('login') }}" class="active">Login</a>
			</div>

	<form action="/getflightsbydate" method="post">
    <input placeholder="source" name="source" required></input>
    <input placeholder="destination" name="destination" required></input>
    <input placeholder="dept_date" name="dept_date" required></input>
    <button type="submit">Add</button>
    </form>


	<form action="/getflightsbynum" method="post">
    <input placeholder="airline" name="airline" required></input>
    <input placeholder="flight_num" name="flight_num" required></input>
    <input placeholder=arr_dept" name="arr_dept" required></input>

    <button type="submit">Add</button>
    </form>
	<br>

	{{flights_by_num}}
	<br>
	{{flights_by_num}}



	</body>
</html>

 

 

 

 

 

 

 

 

 

 

'Backend > Python' 카테고리의 다른 글

Python Flask 웹 페이지 제작(2) - Jinja2 템플릿  (2) 2021.12.21
Python Flask 웹 페이지 제작(1) - 구조, Route  (0) 2021.12.21
백준 코딩 연습  (0) 2021.09.27
리얼센스 code  (0) 2021.02.09
라즈베리 파이 TTS 활용(Python)  (0) 2020.12.09
    'Backend/Python' 카테고리의 다른 글
    • Python Flask 웹 페이지 제작(2) - Jinja2 템플릿
    • Python Flask 웹 페이지 제작(1) - 구조, Route
    • 백준 코딩 연습
    • 리얼센스 code
    땅지원
    땅지원
    신입 개발자의 우당탕탕 기술 블로그

    티스토리툴바