[ES Lab] I tried to develop a WEB application with Python and Flask ②

Introduction

This article is a reminder of a previously developed app. When I was in the third year of university, I became interested in an engineer job in the IT industry while doing job hunting. Then, I came to want to confirm as a self-analysis before getting a job whether I am suitable for system development. Therefore, this WEB application was created with the intention of developing an application in parallel with job hunting. However, there is no point in just copying what is written in the book. Because, through job hunting, I learned that system development has an upstream process and a downstream process. For self-analysis, I think it is necessary to experience not a little about hearings and proposals to customers that are done in the upstream process. Therefore, assuming a virtual customer, we decided to develop a web application to solve the problems that the customer has.

Targets and their challenges

target → I chose university students as the age group that is easiest to imagine. Challenges of the target → ES is the first barrier for job-hunting university students to be selected. However, although many people give feedback and self-reflection in interviews and GD, few people look back on ES. How to solve the problem → I want to provide a database-like application that allows you to look back and share ES.

→ Name it "ES Lab"! !!

Construction environment

Front end: HTML, CSS Backend: Python (framework is Flask) DB:SQLite

App overview

The app consists of 4 pages.

  1. Login page スクリーンショット 2020-12-12 12.55.30.png

  2. List page of registered ES スクリーンショット 2020-12-12 12.55.45.png

  3. Details page of registered ES スクリーンショット 2020-12-12 12.55.57.png

  4. Edit page of registered ES スクリーンショット 2020-12-12 12.56.19.png

  5. Page for new registration of ES スクリーンショット 2020-12-12 12.56.29.png


Directory structure diagram

├── ESLab_blog
│   ├── ESLab_blog.db
│   ├── __init__.py
│   ├── config.py
│   ├── models
│   │   └── entries.py
│   ├── scripts
│   │   └── db.py
│   ├── static
│   │   ├── css
│   │   │   ├── index.css
│   │   │   ├── layout.css
│   │   │   ├── login.css
│   │   │   ├── new.css
│   │   │   └── show.css
│   │   └── images
│   │       ├── ESLab-instraction.jpg
│   │       ├── ESLab.jpg
│   │       ├── ESLab_logo.png
│   │       ├── instraction.png
│   ├── templates
│   │   ├── entries
│   │   │   ├── edit.html
│   │   │   ├── index.html
│   │   │   ├── new.html
│   │   │   └── show.html
│   │   ├── layout.html
│   │   └── login.html
│   └── views
│       ├── __init__.py
│       ├── entries.py
│       └── views.py
├── manage.py
├── server.py


Explanation of structural drawing

ESLab_blog/ESLab_blog.db It is a DB for saving the registered ES. Implemented in SQLite3. ESLab_blog/init.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object("ESLab_blog.config")
db = SQLAlchemy(app)

from ESLab_blog.views import views, entries

ESLab_blog/config.py

SQLALCHEMY_DATABASE_URI = "sqlite:///ESLab_blog.db"
SQLALCHEMY_TRACK_MODIFICATIONS = True
DEBUG = True
USERNAME = "**************"
PASSWORD = "**************"
SECRET_KEY = "**********************"

ESLab_blog/models/entries.py Defines a DB model.

from ESLab_blog import db
from datetime import datetime

class Entry(db.Model):
    __tablename__ = 'entries'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(50), unique=False)
    company = db.Column(db.String(50), unique=False)
    passed = db.Column(db.Integer, primary_key=False)
    text = db.Column(db.Text)
    add_text = db.Column(db.Text)
    created_at = db.Column(db.DateTime)

    def __init__(self, title=None,company=None, passed=None, text=None, add_text=None):
        self.title = title
        self.company = company
        self.passed = passed
        self.text = text
        self.add_text = add_text
        self.created_at = datetime.utcnow()

    def __repr__(self):
        return '<Entry id:{} title:{} text:{}>'.format(self.id, self.title, self.text)

ESLab_blog/scripts/db.py

from flask_script import Command
from ESLab_blog import db

class InitDB(Command):
    "create database"

    def run(self):
        db.create_all()

ESLab_blog/static/css/

Flask seems to automatically recognize the css files in this directory. Some will be posted.

layout.css


@charset "utf-8";

* {
margin: 0px;
padding: 0px;
}

.header {
background-color: #333333;
font-family: arial;
height: 90px;
}

.header a {
color: #ffffff;
}

.header a:visited {
color: #ffffff;
}

.logo {
float: left;
height: 90px;
}

ul {
list-style: none;
}

li {
float: right;
padding-right: 10px;
}

.flash {
background-color: #da3c41;
font-family: arial;
color: #ffffff;
height: 40px;
}

.message {
margin-left:10px;
}

.body-container {
font-family: arial;
padding: 0 5px;
background-color: #666666;
height: 100%;
}

.footer {
font-size: 15px;
color: #ffffff;
background-color: #333333;
height:50px;
padding: 10px 0 0 10px;
font-family: arial;
}

ESLab_blog/static/images/ Flask seems to automatically recognize the image files in this directory.

ESLab_blog/templates/ Flask seems to automatically recognize the html files in this directory. Some will be posted.

layout.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/static/css/layout.css">
    <link rel="stylesheet" href="/static/css/login.css">
    <link rel="stylesheet" href="/static/css/index.css">
    <link rel="stylesheet" href="/static/css/show.css">
    <link rel="stylesheet" href="/static/css/new.css">
    <title>ESLab</title>
</head>
<body>

<div class="container">
    <div class="header">
        <a href="{{ url_for('show_entries') }}"><img class="logo" src="/static/images/ESLab_logo.png "></a>

        <div>
            <ul>
                {% if not session.logged_in %}
                <li><a href="{{ url_for('login') }}">Login</a></li>
                {% else %}
                <li><a href="{{ url_for('new_entry') }}">sign up</a></li>
                <li><a href="{{ url_for('logout') }}">Logout</a></li>
                {% endif %}
            </ul>
        </div>
    </div>

    {% for message in get_flashed_messages() %}
    <div class="flash">
        <div class="message">{{ message }}</div>
    </div>
    {% endfor %}

    <div class="blog-body">
        {% block body %}{% endblock %}
    </div>
</div>
<div class="footer">
    <p>Copyright © 2020 ESLab All Rights Resarved.</p>
</div>
</body>
</html>

ESLab_blog/views/entries.py

I'm routing Flask.

from flask import *
from ESLab_blog import app
from ESLab_blog.models.entries import Entry
from ESLab_blog import db

@app.route('/')
def show_entries():
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    entries = Entry.query.order_by(Entry.id.desc()).all()
    return render_template("entries/index.html", entries=entries)

@app.route("/entries", methods=["POST"])
def add_entry():
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    # db.create_all()
    entry = Entry(
        title=request.form["title"],
        company=request.form["company"],
        passed=request.form["passed"],
        text=request.form["text"],
        add_text=request.form["add_text"]
    )
    db.session.add(entry)
    db.session.commit()
    flash("A new article has been created")
    return redirect(url_for("show_entries"))

@app.route("/entries/new", methods=["GET"])
def new_entry():
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    return render_template("entries/new.html")

@app.route("/entries/<int:id>", methods=["GET"])
def show_entry(id):
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    entry = Entry.query.get(id)
    return render_template(("entries/show.html"), entry=entry)

@app.route("/entries/<int:id>/edit", methods=["GET"])
def edit_entry(id):
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    entry = Entry.query.get(id)
    return render_template("entries/edit.html", entry=entry)

@app.route("/entries/<int:id>/update", methods=["POST"])
def update_entry(id):
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    entry = Entry.query.get(id)
    entry.title = request.form["title"]
    entry.company = request.form["company"]
    entry.passed = request.form["passed"]
    entry.text = request.form["text"]
    entry.add_text = request.form["add_text"]
    db.session.merge(entry)
    db.session.commit()
    flash("ES has been updated")
    return redirect(url_for("show_entries"))

@app.route("/entries/<int:id>/delete", methods=["POST"])
def delete_entry(id):
    if not session.get("logged_in"):
        return redirect(url_for("login"))
    entry = Entry.query.get(id)
    db.session.delete(entry)
    db.session.commit()
    flash("ES has been deleted")
    return redirect(url_for("show_entries"))

ESLab_blog/views/views.py

Only login and logout are separated in the routing.

from flask import *
from ESLab_blog import app
from ESLab_blog.models.entries import Entry
from ESLab_blog import db

@app.route("/login", methods=["GET", "POST"])
def login():
    error = None
    if request.method == "POST":
        if request.form["username"] != app.config["USERNAME"]:
            flash("Username is different")
        elif request.form["password"] != app.config["PASSWORD"]:
            flash("Password is different")
        else:
            session["logged_in"] = True
            flash("You are now logged")
            return redirect(url_for("show_entries"))
    return render_template("login.html")

@app.route("/logout")
def logout():
    session.pop("logged_in", None)
    flash("logged out")
    return redirect(url_for("show_entries"))

manage.py

The app is running.

from flask_script import Manager
from ESLab_blog import app

from ESLab_blog.scripts.db import InitDB

if __name__ == "__main__":
    manager = Manager(app)
    manager.add_command("init_db", InitDB())
    manager.run()

server.py We have launched a WEB server.

from ESLab_blog import app

if __name__ == "__main__":
    app.run(host='0.0.0.0')

Try it out

I tried deploying to heroku. https://shukatsu-eslab.herokuapp.com

Username: abc Password: 123

It is very convenient to be able to register ES, but when I think about using it, I'm likely to be told that Excel is fine. I think that it is easy to see to some extent because there is a list page, but I felt that I needed a point that would be a good idea.

Based on that idea, I started to develop the next app with a big swell. →https://qiita.com/takahashiriki/private/286f5bd7da8ab45701e2

Recommended Posts

[ES Lab] I tried to develop a WEB application with Python and Flask ②
I want to make a web application using React and Python flask
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to make a todo application using bottle with python
Steps to develop a web application in Python
Launch a web server with Python and Flask
I tried to discriminate a 6-digit number with a number discrimination application made with python
Web application with Python + Flask ② ③
Web application with Python + Flask ④
I tried to draw a route map with Python
Parse and visualize JSON (Web application ⑤ with Python + Flask)
I tried to automatically generate a password with Python3
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried web scraping with python.
I made a simple book application with python + Flask ~ Introduction ~
I tried to make GUI tic-tac-toe with Python and Tkinter
I made a web application that maps IT event information with Vue and Flask
[5th] I tried to make a certain authenticator-like tool with python
[2nd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I made a Nyanko tweet form with Python, Flask and Heroku
I tried to create a list of prime numbers with python
I made a server with Python socket and ssl and tried to access it from a browser
I tried a functional language with Python
[Python] A quick web application with Bottle!
I tried to create Bulls and Cows with a shell program
I also tried to imitate the function monad and State monad with a generator in Python
[4th] I tried to make a certain authenticator-like tool with python
I tried to easily detect facial landmarks with python and dlib
I tried to make a Web API
Run a Python web application with Docker
[1st] I tried to make a certain authenticator-like tool with python
I tried benchmarking a web application framework
I made a WEB application with Django
[AWS] Flask application deployment version that tried to build a Python environment with eb [Elastic Beanstalk]
Python: I tried to make a flat / flat_map just right with a generator
I tried to communicate with a remote server by Socket communication with Python.
I made a web application in Python that converts Markdown to HTML
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to develop a Formatter that outputs Python logs in JSON
[GCP] Procedure for creating a web application with Cloud Functions (Python + Flask)
[Streamlit] I hate JavaScript, so I make a web application only with Python
[Outlook] I tried to automatically create a daily report email with Python
I tried to build a Mac Python development environment with pythonz + direnv
Start a web server using Bottle and Flask (I also tried using Apache)
I tried to create a sample to access Salesforce using Python and Bottle
I tried web scraping using python and selenium
I made a GUI application with Python + PyQt5
I want to make a game with Python
I tried Jacobian and partial differential with python
I tried to get CloudWatch data with Python
I tried function synthesis and curry with python
I tried to output LLVM IR with Python
I tried to automate sushi making with python
I want to write to a file with Python
I made a Mattermost bot with Python (+ Flask)
[AWS] Flask application deployment preparation edition that tried to build a Python environment with eb [Elastic Beanstalk]
I tried to automate internal operations with Docker, Python and Twitter API + bonus
When I tried to create a virtual environment with Python, it didn't work