Run Python Flask with SQLite
In this guide we create and deploy a Python Flask application using SQLite. To run this example, follow these steps:
-
Install the
kraft
CLI tool and a container runtime engine, e.g. Docker. -
Clone the
examples
repository andcd
into theexamples/python3.12-flask3.0-sqlite/
directory:
git clone https://github.com/kraftcloud/examplescd examples/python3.12-flask3.0-sqlite/
Make sure to log into Unikraft Cloud by setting your token and a metro close to you.
We use fra0
(Frankfurt, π©πͺ) in this guide:
# Set Unikraft Cloud access tokenexport UKC_TOKEN=token# Set metro to Frankfurt, DEexport UKC_METRO=fra0
When done, invoke the following command to deploy this application on Unikraft Cloud:
kraft cloud deploy -p 443:8080 -M 512 .
[β] Deployed successfully! β βββββββββββ name: python312-flask30-sqlite-qodkd βββββββββββ uuid: e00e7aca-962d-409c-87c2-c245ca08b54b ββββββββββ state: running ββββββββββββ url: https://lingering-orangutan-840mmdvd.fra0.kraft.host ββββββββββ image: python312-flask30-sqlite@sha256:bdb0bf35a9675b9b3836cbb626606da0606334d91768c7ba31195c3062d6f517 ββββββ boot time: 166.25 ms βββββββββ memory: 512 MiB ββββββββ service: lingering-orangutan-840mmdvd βββ private fqdn: python312-flask30-sqlite-qodkd.internal βββββ private ip: 172.16.3.3 βββββββββββ args: /usr/bin/python3 /app/server.py
In this case, the instance name is python312-flask30-sqlite-qodkd
and the URL is https://lingering-orangutan-840mmdvd.fra0.kraft.host
.
They are different for each run.
Use curl
to query the Unikraft Cloud instance of the Python-based HTTP web server:
curl https://young-night-5fpf0jj8.fra0.kraft.host
<!doctype html><html lang="en"> [...] <h1> Welcome to FlaskBlog </h1>
<a href="/1"> <h2>First Post</h2> </a> <span class="badge badge-primary">2024-02-15 22:01:07</span> <a href="/1/edit"> <span class="badge badge-warning">Edit</span> </a> <hr>
<a href="/2"> <h2>Second Post</h2> </a></html>
At any point in time, you can list information about the instance:
kraft cloud instance list
NAME FQDN STATE CREATED AT IMAGE MEMORY ARGS BOOT TIMEpython312-flask30-sqlite-qodkd lingering-orangutan-840mmdvd.fra0.kraft.host running 1 minute ago python312-flask30-sqlite@sha256... 512 MiB /usr/bin/python3 /app/server.py 166250us
When done, you can remove the instance:
kraft cloud instance remove python312-flask30-sqlite-qodkd
Implementation Details
The application uses several files, listed below:
schema.sql
: SQL schema for the databaseinit_db.py
: script to initialized the database file fromschema.sql
in/app/database.db
server.py
+templates/
: the actual Flask-based implementation: Python source code file and HTML template filesrequirements.txt
:pip
configuration file to install required packages: Flask and SQLiteKraftfile
: the Unikraft Cloud specificationDockerfile
: the Docker-specified application filesystem
DROP TABLE IF EXISTS posts;
CREATE TABLE posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, title TEXT NOT NULL, content TEXT NOT NULL);
import sqlite3
connection = sqlite3.connect('/app/database.db')
with open('schema.sql') as f: connection.executescript(f.read())
cur = connection.cursor()
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)", ('First Post', 'Content for the first post') )
cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)", ('Second Post', 'Content for the second post') )
connection.commit()connection.close()
[...]@app.route('/<int:id>/delete', methods=('POST',))def delete(id): post = get_post(id) conn = get_db_connection() conn.execute('DELETE FROM posts WHERE id = ?', (id,)) conn.commit() conn.close() flash('"{}" was successfully deleted!'.format(post['title'])) return redirect(url_for('index'))
if __name__ == '__main__': app.run(host='0.0.0.0', port=8080)
flask>=3.0,<3.1pysqlite3
spec: v0.6
runtime: python:3.12
rootfs: ./Dockerfile
cmd: ["/usr/bin/python3", "/app/server.py"]
FROM python:3.12-bookworm AS build
WORKDIR /app
COPY requirements.txt /app/ RUN pip3 install -r requirements.txt βno-cache-dir
COPY . /app/ RUN python3 init_db.py
FROM scratch
COPY βfrom=build /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 /usr/lib/x86_64-linux-gnu/libsqlite3.so.0 COPY βfrom=build /usr/local/lib/python3.12 /usr/local/lib/python3.12 COPY βfrom=build /app /app
Lines in the Kraftfile
have the following roles:
-
spec: v0.6
: The currentKraftfile
specification version is0.6
. -
runtime: python:3.12
: The Unikraft runtime kernel to use is Python 3.12. -
rootfs: ./Dockerfile
: Build the application root filesystem using theDockerfile
. -
cmd: ["/usr/bin/python3", "/app/server.py"]
: Use/usr/bin/python3 /app/server.py
as the starting command of the instance.
Lines in the Dockerfile
have the following roles:
-
FROM scratch
: Build the filesystem from thescratch
container image, to create a base image. -
COPY
rules result in the copying of required files. Therequirements.txt
file is copied before runningpip3 install
. Other files (includingschema.sql
,init_db.py
) are copied for the initialization of the database. -
RUN
commands trigger actions such as installing Python packages and initializing the database. -
The relevant contents required by the application are copied to the new
scratch
image:- the SQLite dynamic library:
/usr/lib/x86_64-linux-gnu/libsqlite3.so.0
- the Python package files:
/usr/local/lib/python3.12
- the
/app
directory
- the SQLite dynamic library:
Customize your Application
To customize the application, update application files in the repository:
schema.sql
: Update the database schema.server.py
,templates/
: Update the Flask application..requirements.txt
,Dockerfile
: Update the list of Python packages used by the application.Kraftfile
: Update the command line used to start the application.
The following options are available for customizing the application:
-
If only updating the implementation in the
server.py
source file ortemplate/
directory, and the database schema inschema.sql
, no other change is required. -
If new files are added, these have to be copied in the application filesystem, using the
COPY
command in theDockerfile
. -
If new dependencies are added in
requirements.txt
, theRUN pip3 install
in theDockerfile
command should take care of everything. It may be the case that other files, such as the/usr/lib/x86_64-linux-gnu/libsqlite3.so.0
for SQLite, are required to be copied viaCOPY
commands in theDockerfile
. More extensive changes may require expanding theDockerfile
with additionalDockerfile
commands. -
If a new Python source file is added thatβs running the
main()
function, update thecmd
line in theKraftfile
and replaceserver.py
to run that file when creating the instance.
Learn More
Use the --help
option for detailed information on using Unikraft Cloud:
kraft cloud --help
Or visit the CLI Reference.