Flask
Simple example
And Easy to Setup:
Video streaming
#!/usr/bin/env python
from flask import Flask, render_template, Response
from camera import Camera
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen(camera):
while True:
frame = camera.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
@app.route('/video_feed')
def video_feed():
return Response(gen(Camera()),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
File Uploading
<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>
Following is the Python code of Flask application:
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
@app.route('/upload')
def upload_file():
return render_template('upload.html')
@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return 'file uploaded successfully'
if __name__ == '__main__':
app.run(debug = True)
이미지 파일 메모리 업로드/다운로드
from http import HTTPStatus
from io import BytesIO
from PIL import Image
from flask import jsonify, request, send_file
class GlobalMemory:
def __init__(self):
self.snapshot = bytes()
__global_memory__ = GlobalMemory()
@app.route("/snapshot", methods=["POST"])
def post_snapshot():
file_key = "file"
if file_key not in request.files:
return "No file part", HTTPStatus.BAD_REQUEST
file = request.files[file_key]
if not file.filename:
return "No selected file", HTTPStatus.BAD_REQUEST
img = Image.open(file)
img_bytes = BytesIO()
img.save(img_bytes, format=img.format)
global __global_memory__
__global_memory__.snapshot = img_bytes.getvalue()
return jsonify({}), HTTPStatus.OK
@app.route("/snapshot", methods=["GET"])
def get_snapshot():
global __global_memory__
if __global_memory__.snapshot is None:
return "No image available", HTTPStatus.NOT_FOUND
img_bytes = __global_memory__.snapshot
return send_file(BytesIO(img_bytes), mimetype="image/jpeg")
curl 파일 업로드 명령:
curl -X POST -F '[email protected]' http://127.0.0.1:5001/snapshot
curl 파일 다운로드 명령:
requests 라이브러리 사용:
import requests
image_file_descriptor = open('test.jpg', 'rb')
# Requests makes it simple to upload Multipart-encoded files
files = {'file': image_file_descriptor}
url = '...'
requests.post(url, files=files)
image_file_descriptor.close()
Example
Extract file from file storage object in flask
How to get http headers in flask?
request.headers
is a dictionary, so you can also get your header like you would any dictionary:
Displaying opencv image using python flask
Dynamic URLs in flask
@app.route('post/<variable>', methods=['GET'])
def daily_post(variable):
# do your code here
return render_template("template.html",para1=meter1, para2=meter2)
Ecosystem
- Jinja2: Template engine.
- Werkzeug: WSGI Toolkit
- SQLAlchemy (via Flask-SQLAlchemy)
- WTForms (via Flask-WTF)
See also
Favorite site
- Flask의 세계에 오신것을 환영합니다
- Designing a RESTful API with Python and Flask
- 파이썬 플라스크 프레임워크 소개
- (Python) Flask 시작하기
Compare
- Python: 4개의 Web Frameworks 비교 (Pyramid, Bottle, Django, Flask)
- Flask vs. Ruby on Rails
- Django 와 Flask 비교
- Django vs Flask, 까봅시다!
Guide
Tutorials
References
-
How_To_Structure_Large_Flask_Applications_-_ko.pdf ↩