|
1 |
| -import os |
2 |
| - |
3 |
| -from flask import Flask, abort, render_template, request, send_file |
4 |
| -from flask_sqlalchemy import SQLAlchemy |
5 |
| -from libcloud.storage.drivers.local import LocalStorageDriver |
6 |
| -from libcloud.storage.providers import get_driver |
7 |
| -from libcloud.storage.types import ( |
8 |
| - ContainerAlreadyExistsError, |
9 |
| - ObjectDoesNotExistError, |
10 |
| - Provider, |
11 |
| -) |
12 |
| -from sqlalchemy_file import FileField, ImageField |
13 |
| -from sqlalchemy_file.exceptions import ValidationError |
14 |
| -from sqlalchemy_file.processors import ThumbnailGenerator |
15 |
| -from sqlalchemy_file.storage import StorageManager |
16 |
| -from sqlalchemy_file.validators import ContentTypeValidator, SizeValidator |
17 |
| - |
18 |
| -app = Flask(__name__) |
19 |
| -app.config[ |
20 |
| - "SQLALCHEMY_DATABASE_URI" |
21 |
| -] = "sqlite:////tmp/example.db?check_same_thread=False" |
22 |
| -db = SQLAlchemy(app, engine_options={"echo": True}) |
23 |
| - |
24 |
| - |
25 |
| -class Book(db.Model): |
26 |
| - __tablename__ = "books" |
27 |
| - isbn = db.Column(db.Integer, primary_key=True) |
28 |
| - author = db.Column(db.String(100), nullable=False) |
29 |
| - title = db.Column(db.String(100), nullable=False) |
30 |
| - cover = db.Column( |
31 |
| - ImageField( |
32 |
| - upload_storage="images", |
33 |
| - validators=[SizeValidator("16M")], |
34 |
| - processors=[ThumbnailGenerator((50, 50))], |
35 |
| - ) |
36 |
| - ) |
37 |
| - document = db.Column( |
38 |
| - FileField( |
39 |
| - upload_storage="documents", |
40 |
| - validators=[ |
41 |
| - SizeValidator("5M"), |
42 |
| - ContentTypeValidator( |
43 |
| - allowed_content_types=[ |
44 |
| - "application/pdf", |
45 |
| - "application/msword", |
46 |
| - "application/vnd.openxmlformats-officedocument.wordprocessingml.document", |
47 |
| - ] |
48 |
| - ), |
49 |
| - ], |
50 |
| - ) |
51 |
| - ) |
52 |
| - |
53 |
| - |
54 |
| -@app.route("/", methods=("GET", "POST")) |
55 |
| -def index(): |
56 |
| - error = None |
57 |
| - if request.method == "POST": |
58 |
| - try: |
59 |
| - book = Book( |
60 |
| - author=request.form["author"], |
61 |
| - title=request.form["title"], |
62 |
| - ) |
63 |
| - if "cover" in request.files and request.files["cover"].filename != "": |
64 |
| - book.cover = request.files["cover"] |
65 |
| - if "document" in request.files and request.files["document"].filename != "": |
66 |
| - book.document = request.files["document"] |
67 |
| - db.session.add(book) |
68 |
| - db.session.commit() |
69 |
| - except ValidationError as err: |
70 |
| - error = err |
71 |
| - db.session.rollback() |
72 |
| - return render_template( |
73 |
| - "index.html", books=Book.query.all(), form=request.form, error=error |
74 |
| - ) |
75 |
| - |
76 |
| - |
77 |
| -@app.route("/medias/<storage>/<file_id>") |
78 |
| -def serve_files(storage, file_id): |
79 |
| - try: |
80 |
| - file = StorageManager.get_file(f"{storage}/{file_id}") |
81 |
| - if isinstance(file.object.driver, LocalStorageDriver): |
82 |
| - """If file is stored in local storage, just return a |
83 |
| - FileResponse with the fill full path.""" |
84 |
| - return send_file( |
85 |
| - file.get_cdn_url(), |
86 |
| - mimetype=file.content_type, |
87 |
| - download_name=file.filename, |
88 |
| - ) |
89 |
| - elif file.get_cdn_url() is not None: |
90 |
| - """If file has public url, redirect to this url""" |
91 |
| - return app.redirect(file.get_cdn_url()) |
92 |
| - else: |
93 |
| - """Otherwise, return a streaming response""" |
94 |
| - return app.response_class( |
95 |
| - file.object.as_stream(), |
96 |
| - mimetype=file.content_type, |
97 |
| - headers={"Content-Disposition": f"attachment;filename={file.filename}"}, |
98 |
| - ) |
99 |
| - except ObjectDoesNotExistError: |
100 |
| - abort(404) |
101 |
| - |
102 |
| - |
103 |
| -if __name__ == "__main__": |
104 |
| - os.makedirs("/tmp/storage", 0o777, exist_ok=True) |
105 |
| - driver = get_driver(Provider.LOCAL)("/tmp/storage") |
106 |
| - |
107 |
| - # cls = get_driver(Provider.MINIO) |
108 |
| - # driver = cls("minioadmin", "minioadmin", secure=False, host="127.0.0.1", port=9000) |
109 |
| - |
110 |
| - try: |
111 |
| - driver.create_container(container_name="images") |
112 |
| - except ContainerAlreadyExistsError: |
113 |
| - pass |
114 |
| - try: |
115 |
| - driver.create_container(container_name="documents") |
116 |
| - except ContainerAlreadyExistsError: |
117 |
| - pass |
118 |
| - |
119 |
| - StorageManager.add_storage("images", driver.get_container(container_name="images")) |
120 |
| - StorageManager.add_storage( |
121 |
| - "documents", driver.get_container(container_name="documents") |
122 |
| - ) |
123 |
| - |
124 |
| - db.create_all() |
125 |
| - app.run(debug=True) |
0 commit comments