[PYTHON] Steps to set up Pipenv, create a CRUD app with Flask, and containerize it with Docker

Background of writing the article

I will retire from my current SIer this month, and I am thinking of becoming an engineer around infrastructure. When building an infrastructure and CI / CD environment that makes full use of the public cloud in recent years, even a legacy engineer like me should avoid building apps in various languages or creating apps for communication confirmation. It is around this time that I feel that I can no longer pass.

I wanted to do my best to build various languages and make a little web application, so this time I described the procedure to create a Flask application (just touching it) with Python and Pipenv and make it a Docker container.

Installing Pipenv

In recent years, Python environment construction seems to be built using a tool called Pipenv, so I tried using it. It's like JavaScript npm and easy to use.

pip install pipenv

Creating an app project

mkdir flask-app
cd flask-app

This time I will use Python 3.8.

pipenv --python 3.8
pipenv install flask
pipenv install --dev autopep8

Create an empty file to be created.

mkdir src
touch src/main.py
touch Dockerfile
touch .dockerignore

Add to the scripts section of the Pipfile.

[scripts]
start = "python src/main.py"

Flask application coding

It will be a code written by a Python amateur, but I created it like the following.

src/main.py


import sqlite3
import flask

app = flask.Flask(__name__)


def get_db():
    db = getattr(flask.g, '_database', None)
    if db is None:
        db = flask.g._database = sqlite3.connect('mydb.sqlite')
    return db


@app.teardown_appcontext
def close_conn(exception):
    db = getattr(flask.g, '_database', None)
    if db is not None:
        db.close()


@app.route('/todos/<id>', methods=['GET'])
@app.route('/todos', methods=['GET', 'POST'])
def todos(id=None):
    db = get_db()

    #Create a table when you receive a request
    curs = db.cursor()
    curs.execute(
        'create table if not exists todos('
        'id integer primary key autoincrement, title string)'
    )

    id = flask.request.values.get('id', id)

    if flask.request.method == 'GET' and id is not None:
        curs.execute('select * from todos where id = {}'.format(id))
        response = curs.fetchone()
        if response is not None:
            id, title = response
            return flask.jsonify(todo={"id": id, "title": title}), 200

        return flask.jsonify(message='resource not found'), 400

    if flask.request.method == 'GET':
        curs.execute('select * from todos')
        response = curs.fetchall()
        todos = []
        for todo in response:
            id, title = todo
            todos.append({"id": id, "title": title})

        return flask.jsonify(todos=todos), 200

    if flask.request.method == 'POST':
        title = flask.request.json['title']
        curs.execute('insert into todos(title) values("{}")'.format(title))
        db.commit()
        return flask.jsonify(message='created new toto')


def main():
    app.debug = True
    app.run(host='0.0.0.0', port=5000)


if __name__ == "__main__":
    main()

At this point it should work in your local environment.

pipenv run start

 * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 208-926-045

Hit the curl command to check.

curl -XPOST -H 'Content-Type: application/json' localhost:5000/todos -d '{"title": "new task1"}'
curl -XPOST -H 'Content-Type: application/json' localhost:5000/todos -d '{"title": "new task2"}'
curl localhost:5000/todos
curl localhost:5000/todos/1

Creating and building a Dockerfile

I don't know the practice when combined with Pipenv, but I made it with Simple Is Best.

FROM python:3.8

ENV LC_ALL=C.UTF-8 \
    LANG=C.UTF-8

WORKDIR /app
COPY . .

RUN pip install pipenv
RUN pipenv install

CMD ["pipenv", "run", "start"]

EXPOSE 5000

Also create a .dockerignore file.

.dockerignore


*.sqlite
.git

Build.

docker image build -t flaskapp:latest . 

Start the container (starting the local port as 15000).

docker container run -it -p 15000:5000 --rm flaskapp:latest

 * Serving Flask app "main" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 954-331-726

It's OK if you can confirm by hitting the curl command.

curl -XPOST -H 'Content-Type: application/json' localhost:15000/todos -d '{"title": "new task1"}'
curl -XPOST -H 'Content-Type: application/json' localhost:15000/todos -d '{"title": "new task2"}'
curl localhost:15000/todos
curl localhost:15000/todos/1

in conclusion

I was accustomed to npm and yarn with nodejs, so I avoided building a python environment, but I found Pipenv useful. I didn't know Pipenv, so I felt like I had lost it.

For the time being, from the perspective of an infrastructure engineer (subjective), I'm satisfied because I've done so far. We will do our best to provide the environment without bothering the application engineer.

However, although I didn't remember much until about five years ago, the changes in the environment surrounding IT technology these days are tremendous. It has been left behind, but I am desperately trying to catch up with it.

Recommended Posts

Steps to set up Pipenv, create a CRUD app with Flask, and containerize it with Docker
I want to create a pipfile and reflect it in docker
Create a simple web app with flask
Create a web service with Docker + Flask
Set up a Lambda function and let it work with S3 events!
Steps to create a Twitter bot with python
How to create a multi-platform app with kivy
Build a flask app made with tensorflow and dlib to work on centos7
Create a web app that converts PDF to text using Flask and PyPDF2
I set up TensowFlow and was addicted to it, so make a note
Create a native GUI app with Py2app and Tkinter
[Linux] Create a self-signed certificate with Docker and apache
From installing Flask on CentOS to making it a service with Nginx and uWSGI
It was a little difficult to do flask with the docker version of nginx-unit
Quickly create a Python data analysis dashboard with Streamlit and deploy it to AWS
Steps to quickly create a deep learning environment on Mac with TensorFlow and OpenCV
How to deploy a web app made with Flask to Heroku
How to set up WSL2 on Windows 10 and create a study environment for Linux commands
Create a deploy script with fabric and cuisine and reuse it
Create a Todo app with Django ① Build an environment with Docker
How to set a shortcut to switch full-width and half-width with IBus
Create a temporary file with django as a zip file and return it
I tried to create Bulls and Cows with a shell program
Create a C ++ and Python execution environment with WSL2 + Docker + VSCode
Create a simple Python development environment with VS Code and Docker
Steps to create a Django project
Creating a Flask server with Docker
Creating a simple app with flask
Set up a yum repository server on CentOS7 system and refer to it locally and from other servers.
Introduction and usage of Python bottle ・ Try to set up a simple web server with login function
Deploy a Python app on Google App Engine and integrate it with GitHub
Send mail with mailx to a dummy SMTP server set up with python.
Build your Django app on Docker and deploy it to AWS Fargate
Steps to create a Python virtual environment with VS Code on Windows
I set the environment variable with Docker and displayed it in Python
How to make a container name a subdomain and make it accessible in Docker
Create a Todo app with Django ④ Implement folder and task creation functions
Create a decision tree from 0 with Python and understand it (5. Information Entropy)
Create a GUI app with Python's Tkinter
I came up with a way to create a 3D model from a photo Part 02 Image loading and vertex drawing
Create a Python-GUI app in Docker (PySimpleGUI)
Create a simple app that incorporates the Fetch API of Ajax requests in Flask and explain it quickly
Create an API to convert PDF files to TIF images with FastAPI and Docker
When I tried to create a virtual environment with Python, it didn't work
[ES Lab] I tried to develop a WEB application with Python and Flask ②
I want to write an element to a file with numpy and check it.
Zip-compress any file with the [shell] command to create a file and delete the original file.
Create a stacked graph corresponding to both positive and negative directions with matplotlib
Load a photo and make a handwritten sketch. With zoom function. Tried to make it.
Install and set Jupyter Notebook to create a study note creation environment [Mac]
[Python] How to create a local web server environment with SimpleHTTPServer and CGIHTTPServer
When I tried to create a project using Python on Docker with PyCharm, it didn't work, but it worked with Docker Compose.
Set up a simple HTTPS server with asyncio
Set up a local server with Go-File upload-
Create an image composition app with Flask + Pillow
Create a bulletin board with Heroku, Flask, SQLAlchemy
Set up a local server with Go-File download-
Create a Mac app using py2app and Python3! !!
How to set up a Google Colab environment with Coursera's advanced machine learning courses
How to set up a VPN gateway to establish a connection between Alibaba Cloud and AWS
[Introduction to system trading] I drew a Stochastic Oscillator with python and played with it ♬