예제 1)
index.html
<html>
<head>
<script type="text/javascript" src="{{ url_for('static', filename = 'hello.js') }}"></script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
hello.js
function sayHello() {
alert("Hello World")
}
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)
atom-html-preview 설치하기
예제 2)
student.html
<html>
<body>
<form action="http://localhost:5000/result" method="POST">
<p>Name <input type="text" name="Name" /></p>
<p>Physics <input type="text" name="Physics" /></p>
<p>Chemistry <input type="text" name="chemistry" /></p>
<p>Maths <input type="text" name="Mathematics" /></p>
<p> <input type="submit" value="submit" /></p>
</form>
</body>
</html>
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def student():
return render_template('student.html')
@app.route('/result', methods=['POST', 'GET'])
def result():
if request.method == 'POST':
result = request.form
return render_template("result.html", result=result)
예제 3 쿠키
https://www.javatpoint.com/flask-cookies
login2.html
<html>
<head>
<title>login</title>
</head>
<body>
<form method="post" action="http://localhost:5000/success">
<table>
<tr><td>Email</td><td><input type='email' name='email'></td></tr>
<tr><td>Password</td><td><input type='password' name='pass'></td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>
success.html
<html>
<head>
<title>success</title>
</head>
<body>
<h2>Login successful</h2>
<a href="/profile">View Profile</a>
</body>
</html>
profile.html
<html>
<head>
<title>profile</title>
</head>
<body>
<h3>{{name}}님 로그인 상태입니다</h3>
</body>
</html>
app.py
from flask import *
app = Flask(__name__)
@app.route('/login2')
def login2():
return render_template("login2.html")
@app.route('/success', methods=['POST'])
def success():
if request.method == "POST":
email = request.form['email']
password = request.form['pass']
if password == "sa":
resp = make_response(render_template('success.html'))
resp.set_cookie('email', email)
return resp
else:
return redirect(url_for('error'))
@app.route('/error')
def error():
return "<p><strong>Enter correct password</strong></p>"
@app.route('/profile')
def profile():
email = request.cookies.get('email')
resp = make_response(render_template('profile.html', name=email))
return resp
if __name__ == '__main__':
app.run(debug=True)
예제 4 )
home.html
<html>
<head>
<title>home</title>
</head>
<body>
<h3>Welcome to the website</h3>
<a href="/login">로그인</a><br>
<a href="/profile">프로파일 보기</a><br>
<a href="/logout">로그아웃</a><br>
</body>
</html>
logout.html
<html>
<head>
<title>logout</title>
</head>
<body>
<p>logout successful, click <a href="/login">here</a> to login again</p>
</body>
</html>
login.py
from flask import *
app = Flask(__name__)
app.secret_key = "amustring"
@app.route('/')
def home():
return render_template("home.html")
@app.route('/login')
def login():
return render_template("login2.html")
@app.route('/success', methods=["POST"])
def success():
if request.method == "POST":
session['email'] = request.form['email']
return render_template('success.html')
@app.route('/logout')
def logout():
if 'email' in session:
session.pop('email', None) # pop 메소드로 세션 변수 제거
return render_template('logout.html')
else:
return '<p>user already logged out</p>'
@app.route('/profile')
def profile():
if 'email' in session:
email = session['email']
return render_template('profile.html', name=email)
else:
return '<p>Please login first</p>'
if __name__ == '__main__':
app.run(debug=True)
예제 5 ) Message Flashing
*flash : (불빛으로) 신호를 보내다
index.html
<html>
<body>
<form action="http://localhost:5000/login" method="post">
<p>User Name:</p><p><input type="text" name="username" /></p>
<p>Password:</p><p><input type="password" name="password" /></p>
<p><input type="submit" value="submit" /></p>
</form>
</body>
</html>
login.html
<!doctype html>
<html>
<body>
<h1>Login</h1>
{% if error %}
<p><strong>Error:</strong> {{ error }}
{% endif %}
<form action="http://localhost:5000/login/" method="post">
<dl>
<dt>Username:</dt>
<dd><input type=text name=username value="{{request.form.username }}"></dd>
<dt>Password:</dt>
<dd><input type=password name=password></dd>
</dl>
<p><input type=submit value=Login></p>
</form>
</body>
</html>
flask.py
from flask import *
app = Flask(__name__)
app.secret_key = 'random string'
@app.route('/')
def index():
return render_template('index.html')
@app.route('/login/', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] != 'admin' or \
request.form['password'] != 'admin':
error = 'Invalid username or password. Please try again!'
else:
flash('성공적으로 로그인되었습니다!')
return redirect(url_for('index'))
return render_template('login.html', error=error)
if __name__ == "__main__":
app.run(debug=True)
admin이 아니면 에러
예제 6) 파일 업로드
upload.html
<html>
<body>
<form action="http://localhost:5000/uploader" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>
</body>
</html>
app.py
from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/')
def upload():
return render_template('upload.html')
@app.route('/uploader', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save('C:/dev/FlaskIntro/uploads/' + secure_filename(f.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug=True)
예제 7)
home.html
<html>
<head>
<title>home</title>
</head>
<body>
<h3>Welcome to the website</h3>
<a href="/list">학생 목록</a><br>
<a href="/enternew">학생 추가</a><br>
</body>
</html>
student.html
<html>
<body>
<form action="{{ url_for('addrec') }}" method="POST">
<h3>Student Information</h3>
Name<br><input type="text" name="nm" /></br>
Address<br><textarea name="add"></textarea><br>
City<br><input type="text" name="city" /><br>
PINCODE<br><input type="text" name="pin" /><br>
<input type="submit" value="submit" /><br>
</form>
</body>
</html>
list.html
<!doctype html>
<html>
<body>
<table border=1>
<thead>
<td>Name</td>
<td>Address</td>
<td>city</td>
<td>Pincode</td>
</thead>
{% for row in rows %}
<tr>
<td>{{row["name"]}}</td>
<td>{{row["addr"]}}</td>
<td>{{row["city"]}}</td>
<td>{{row['pin']}}</td>
</tr>
{% endfor %}
</table>
<a href="/">Go back to home page</a>
</body>
</html>
result.html
<!doctype html>
<html>
<body>
result of addition : {{ msg }}
<h2><a href="\">go back to home page</a></h2>
</body>
</html>
app.py
import sqlite3 as sql
from flask import Flask, render_template, request
conn = sql.connect('database.db') #database.db 실행하면 파일 생성됨
print("Opened database successfully")
conn.execute(
'CREATE TABLE IF NOT EXISTS students (name TEXT, addr TEXT, city TEXT, pin TEXT)')
print("Table created successfully")
conn.close()
''''''
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
@app.route('/list')
def list():
con = sql.connect("database.db")
con.row_factory = sql.Row
cur = con.cursor()
cur.execute("select * from students")
rows = cur.fetchall()
return render_template("list.html", rows=rows)
@app.route('/enternew')
def new_student():
return render_template('student.html')
@app.route('/addrec', methods=['POST', 'GET'])
def addrec():
if request.method == 'POST':
try:
name = request.form['nm']
addr = request.form['add']
city = request.form['city']
pin = request.form['pin']
with sql.connect("database.db") as con:
cur = con.cursor()
cur.execute("""INSERT INTO students(name, addr, city, pin)
VALUES(?, ?, ?, ?)""", (name, addr, city, pin))
con.commit()
msg = "Record successfully added"
except:
con.rollback()
msg = "error in insert operation"
finally:
return render_template("result.html", msg=msg)
con.close()
if __name__ == '__main__':
app.run(debug=True)
'인공지능 > PYTHON' 카테고리의 다른 글
Crawling and Flask (0) | 2021.06.24 |
---|---|
크롤링 (2) (0) | 2021.06.23 |
Flask (0) | 2021.06.22 |
Python 300제 - 함수 (0) | 2021.06.18 |
Python - w3schools (0) | 2021.06.18 |