How to create an image uploader in Bottle (Python)

Bottle To Uploader By.Python

It is for memos, so it is the minimum content.


Various Ver.


myapp.py


from bottle import route, run, template, request, static_file, url, get, post, response, error, abort, redirect, os
import sys, codecs
import bottle.ext.sqlalchemy
import sqlalchemy
import sqlalchemy.ext.declarative

sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

@route("/")
def html_index():
    return template("index", url=url)

@route("/static/<filepath:path>", name="static_file")
def static(filepath):
    return static_file(filepath, root="./static")

@route("/static/img/<img_filepath:path>", name="static_img")
def static_img(img_filepath):
    return static_img(img_filepath, root="./static/img/")

#File Upload
@get('/upload')
def upload():
    return '''
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="submit" value="Upload"></br>
            <input type="file" name="upload"></br>
        </form>
    '''

@route('/upload', method='POST')
def do_upload():
    upload = request.files.get('upload', '')
    if not upload.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
        return 'File extension not allowed!'
    save_path = get_save_path()
    upload.save(save_path)
    return 'Upload OK. FilePath: %s%s' % (save_path, upload.filename)

def get_save_path():
    path_dir = "./static/img/"
    return path_dir

run(host="0.0.0.0", port=8000, debug=True, reloader=True)

...Omitted because the code is not relevant below

Other

I also wanted to allow external connections, so the run host is not "localhost" Described as "0.0.0.0".

It also adds an image file path for the template.

@ Addition (when uploading multiple files)

myapp.py


#No change

#File Upload
@get('/upload')
def upload():
    return '''
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="submit" value="Upload"></br>
-           <input type="file" name="upload"></br>
+           <input multiple="multiple" name="upload[image_file_name][]" type="file" accept="image/*" id="upload">
        </form>
    '''

@route('/upload', method='POST')
def do_upload():
-   upload = request.files.get('upload', '')
+   pload_files = request.files.getall('upload[image_file_name][]')

-   if not upload.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
-       return 'File extension not allowed!'
-   save_path = get_save_path()
-   upload.save(save_path)
-   return 'Upload OK. FilePath: %s%s' % (save_path, upload.filename)
+   save_path = get_save_path()
+   for count, uplad_file in enumerate(upload_files):
+       upload_img = uplad_file
+       if not upload_img.filename.lower().endswith(('.png', '.jpg', '.jpeg')):
+           return template("no {{uplad_file}}", uplad_file=uplad_file)
+       upload_img.save(save_path)
+   return 'Upload OK. FilePath: %s ImageFiles:%s' % (save_path, pload_files)

#No change below

The key to the update is the use of ʻenumerate`. By using this, you can add indexed elements and store data.

Reference

Template reference URL

-Generating static file links with Python's Bottle framework

Image upload reference URL

-Python learned from Bottle

URL that served as a reference for uploading multiple files

-Convenient zip, enumerate function in for loop -enumerate (iterable, start = 0) (official)

The above is a summary of Bottle that I recently referred to. .. ..

Recommended Posts

How to create an image uploader in Bottle (Python)
How to adjust image contrast in Python
How to create a heatmap with an arbitrary domain in Python
How to use Python Image Library in python3 series
How to create a JSON file in Python
How to crop an image with Python + OpenCV
Create an image with characters in python (Japanese)
python3: How to use bottle (2)
How to develop in Python
python3: How to use bottle (3)
python3: How to use bottle
[Blender x Python] How to create an original object
[Python] How to do PCA in Python
How to use SQLite in Python
How to create an email user
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to use PubChem in Python
How to handle Japanese in Python
An alternative to `pause` in Python
How to swap elements in an array in Python, and how to reverse an array.
[Python] How to write an if statement in one sentence.
[Python Kivy] How to create an exe file with pyinstaller
How to create an ISO file (CD image) on Linux
How to access environment variables in Python
How to know the internal structure of an object in Python
How to dynamically define variables in Python
How to do R chartr () in Python
How to create an NVIDIA Docker environment
How to convert Python to an exe file
[Itertools.permutations] How to put permutations in Python
How to create an instance of a particular class from dict using __new__ () in python
How to work with BigQuery in Python
How to get a stacktrace in python
How to display multiplication table in python
How to extract polygon area in Python
How to check opencv version in python
How to switch python versions in cloud9
How to use __slots__ in Python class
How to dynamically zero pad in Python
How to use regular expressions in Python
Various ways to create an array of numbers from 1 to 10 in Python.
How to display Hello world in python
How to use is and == in Python
How to write Ruby to_s in Python
How to send a visualization image of data created in Python to Typetalk
[Python] Create a linebot to write a name and age on an image
How to use the C library in Python
How to receive command line arguments in Python
How to create a Python virtual environment (venv)
How to clear tuples in a list (Python)
How to embed a variable in a python string
How to implement Discord Slash Command in Python
Summary of how to import files in Python 3
I want to create a window in Python
How to simplify restricted polynomial fit in python
How to implement shared memory in Python (mmap.mmap)
How to create an OCF compliant resource agent
How to get help in an interactive shell
Summary of how to use MNIST in Python