pip install Flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
export FLASK_APP=hello
flask run
예시1. HTTP 메서드 명시 안하면 GET만 작동함.
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
예시2. 다른 HTTP 메서드를 사용하기 위해서는 추가로 명시해줘야 함.
from flask import request
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
return do_the_login()
else:
return show_the_login_form()
url_for('static', filename='style.css')
from flask import render_template
를 통해 template를 return할 수 있다.from flask import render_template
@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
from flask import request
request.args.get('key', '')
@app.route('/login', methods=['POST', 'GET'])
def login():
error = None
if request.method == 'POST':
if valid_login(request.form['username'],
request.form['password']):
return log_the_user_in(request.form['username'])
else:
error = 'Invalid username/password'
# the code below is executed if the request method
# was GET or the credentials were invalid
return render_template('login.html', error=error)
-HTML form에 enctype="multipart/form-data"
를 반드시 적어줘야만 한다. 적지 않으면 브라우저가 파일 전송 자체를 하지 않는다.
from flask import request
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['the_file']
f.save('/var/www/uploads/uploaded_file.txt')
secure_filename()
을 통해 접근해라. 이 함수는 Werkzeug(내장 라이브러리)가 제공한다.from werkzeug.utils import secure_filename
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['the_file']
file.save(f"/var/www/uploads/{secure_filename(f.filename)}")
request.cookies.get('key')
from flask import request
@app.route('/')
def index():
username = request.cookies.get('username')
# use cookies.get(key) instead of cookies[key] to not get a
# KeyError if the cookie is missing.
from flask import make_response
@app.route('/')
def index():
resp = make_response(render_template(...))
resp.set_cookie('username', 'the username')
return resp
abort
는 raise exception과 비슷한 것 같다.from flask import abort, redirect, url_for
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
1. If a response object of the correct type is returned it’s directly 2. returned from the view.
2. If it’s a string, a response object is created with that data and the default parameters.
3. If it’s a dict, a response object is created using jsonify.
4. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status), (response, headers), or (response, status, headers). The status value will override the status code and headers can be a list or dictionary of additional header values.
5. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.
from flask import render_template
@app.errorhandler(404)
def not_found(error):
return render_template('error.html'), 404
from flask import make_response
@app.errorhandler(404)
def not_found(error):
resp = make_response(render_template('error.html'), 404)
resp.headers['X-Something'] = 'A value'
return resp
@app.route("/me")
def me_api():
user = get_current_user()
return {
"username": user.username,
"theme": user.theme,
"image": url_for("user_image", filename=user.image),
}
jsonify
를 호출하면 된다.from flask import jsonify
@app.route("/users")
def users_api():
users = get_all_users()
return jsonify([user.to_json() for user in users])
당장 쓰지 않을 것 같아서 pass
Logging
Hooking in WSGI Middleware
Using Flask Extensions