from flask import Flask

app = Flask(__name__) 
 
# 경로 요청 처리
@app.route('/') 
def home(): 
    return 'hello world!'

# GET, POST 요청 처리
from flask import request

@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == 'POST':
        keyword = request.form[u"keyword"] # localhost/login
        return keyword
    else:
        keyword = request.args[u"keyword"] # localhost/login?keyword=zzzz
        return keyword
    
# render_template 활용
from flask import render_template

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
   return render_template('hello.html', name=name)

# Error Handler
@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404

# Redirect
from flask import abort, redirect, url_for

@app.route('/login')
def login():
    return redirect(url_for('logout'))

@app.route('/logout')
def logout():
    abort(401) # 401 Unauthorized 창 출력

# jsonify (json 형식으로 return)
from flask import jsonify

@app.route('/userinfo')
def get_current_user():
    return jsonify(username='lth',
                   email='lth00ce@example.com',
                   id='lth00ce')

# static - 템플릿에서 사용
# ex) <script src="{{ url_for('static', filename='js/jquery.js') }}> </script>

# multipart request handling (upload)
from flask import request
from werkzeug.utils import secure_filename, send_from_directory

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        print(secure_filename(f.filename))
        print("hello")
        f.save('/home/lee/work-space/venv-prac/static/uploads/' + secure_filename(f.filename))
        return jsonify({"message": "File uploaded successfully"})

# download
app.config['UPLOAD_FOLDER'] = '/home/lee/work-space/venv-prac/static/uploads'
@app.route('/uploads/<path:filename>')
def download_file(filename):
    print(filename)
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename, as_attachment=True, environ=request.environ)

app.run(port=8888, host='0.0.0.0', threaded=True)  # threaded=True 혹은 processes=3 => 병렬 처리