[PYTHON] Create a simple web app with flask

Site to do

http://www.kzfmix.com/flaski/

Prepare environment for flask with virtualenv

See here for how to install and use virtualenv.

$ mkvirtualenv flaski
$ workon flaski

Installation

(flaski):flask_test hoge$ pip install flask
(flaski):flask_test hoge$ pip install sqlalchemy

Set up a web server locally and display Hello World in your browser.

{app.py}


from flask import Flask
app = Flask(__name__)

# http://127.0.0.1:With 5000 as the route("")Access point designation in
# @app.route("hoge")If you specify with etc., http://127.0.0.1:5000/Can describe the operation in hoge.
@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    #Web server launch
    app.run()

And run it with `` `python app.py```, the following will be displayed in standard output.

(flaski)hoge:src hoge$ python app.py 
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Type http://127.0.0.1:5000/ in your browser and you will see the following:

スクリーンショット 2016-05-10 21.35.04.png

SQLite operations with SQLAlchemy

file organization

├── flaski
│   ├── __init__.py
│   ├── database.py
│   └── models.py
├── do_create.py
└── do_insert.py

Check each script and operation

{database.py}


# -*- coding: utf-8 -*-

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import os

# wiki.Specifies to create a db file named db
databese_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'wiki.db')
#Specify sqlite and specify create table.
engine = create_engine('sqlite:///' + databese_file, convert_unicode=True)
#Specify the table create for bind.
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
# declarative_Instantiation of base.
Base = declarative_base()
#Session storage for execution?
Base.query = db_session.query_property()


def init_db():
    import flaski.models
    #Execute create with the contents of Base?
    Base.metadata.create_all(bind=engine)

{models.py}


# -*- coding: utf-8 -*-

from sqlalchemy import Column, Integer, String, Text, DateTime
from flaski.database import Base
from datetime import datetime


class WikiContent(Base):
    __tablename__ = 'wikicontents'                  #table name
    id = Column(Integer, primary_key=True)          #Column 1(id)
    title = Column(String(128), unique=True)        #Column 2(title)
    body = Column(Text)                             #Column 3(body)
    date = Column(DateTime, default=datetime.now()) #Column 4(date)Set default current date and time

    def __init__(self, title=None, body=None, date=None):
        self.title = title
        self.body = body
        self.date = date

    def __repr__(self):
        return '<Title %r>' % (self.title)

{do_create.py}


from flaski.database import init_db
#Create table
init_db()

By executing do_create.py, wiki.db will be created under the flaski directory. Check the contents.

{confirm_sqllite.}


$ > (flaski)hoge:flaski hoge$ sqlite3 wiki.db 
SQLite version 3.8.5 2014-08-15 22:37:57
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE wikicontents (
	id INTEGER NOT NULL, 
	title VARCHAR(128), 
	body TEXT, 
	date DATETIME, 
	PRIMARY KEY (id), 
	UNIQUE (title)
);

{do_insert.py}


from flaski.database import init_db
from flaski.database import db_session
from flaski.models import WikiContent

#The id is a serial number. Specify title and text. date can be entered without permission(model.By default setting of py)
c1 = WikiContent("Flask", "micro framework")  #Column 1:'Flask'Column 2:'micro framework'Create an instance by specifying
db_session.add(c1)                            #insert execution
db_session.commit()                           #commit execution
c2 = WikiContent("python", "pppython")        #Same as above
c3 = WikiContent("kobito", "kakure-momojiri")
db_session.add(c2)
db_session.add(c3)
db_session.commit()

Let's check the table earlier.

{confirm_sqllite2.}


(flaski)hoge:flaski hoge$ sqlite3 wiki.db 
SQLite version 3.8.5 2014-08-15 22:37:57
Enter ".help" for usage hints.
sqlite> select * from wikicontents;
1|Flask|micro framework|2016-05-14 15:04:24.246057
2|python|pppython|2016-05-14 15:04:24.246057
3|kobito|kakure-momojiri|2016-05-14 15:04:24.246057

You can see that 3 records have been inserted.

reference

http://omake.accense.com/static/doc-ja/sqlalchemy/session.html

GET data by linking flask and SQLite

Display the Web page using the table values created in SQLite earlier.

Source code

github

file organization

├── flaski
│   ├── __init__.py
│   ├── database.py
│   └── models.py
├── app.py
├── static
│   └── snake.jpg
└── templates
    ├── index.html
    ├── layout.html
    └── show_content.html

Each script

{app.py}


# -*- coding: utf-8 -*-
"""
 Using SQLAlchemy and Flask get db record.(GET)
"""

from flask import Flask, render_template, abort
from flaski.models import WikiContent

app = Flask(__name__)
app.config['DEBUG'] = True


#Of the started server/Describes the behavior when accessing.
# @app.route("/hoge")If you write in, http://127.0.0.1:5000/You can describe the behavior when accessing with aa.
@app.route("/")
def hello():
    contents = WikiContent.query.all()
    # index.Execute by passing context as an argument to html.
    return render_template("index.html", contents=contents)

#/<title>By specifying index.html title=content.The title is specified. methods=["GET"]Then specify the GET request.
@app.route("/<title>", methods=["GET"])
def show_content(title):
    """
    :param title:Query string for model
    :return:
    """
    #Filter by title from wikicontent table(get by specifying where)first means to get only one line.
    # all()Then, get the result in multiple list format.
    content = WikiContent.query.filter_by(title=title).first()
    if content is None:
        abort(404)
    # show_content.Display html. Pass content as an argument.
    return render_template("show_content.html", content=content)

if __name__ == "__main__":
    #Start the server
    app.run()

snake.jpg snake.jpg

{index.html}


{% extends "layout.html" %}
{% block body %}
<h1>Flaski</h1>
<!-- snake.jpg display-->
<img src="{{url_for('static', filename='snake.jpg')}}" alt="snake"/>
<ul>
<!--For loop of contents passed as an argument-->
{% for content in contents %}
<!-- show_content.Run html.+ {{content.title}}Show.-->
<li><a href="{{url_for('show_content', title=content.title)}}">{{content.title}}</a></li>
{% endfor%}
</ul>
{% endblock %}

{show_content.html}


{% extends "layout.html" %}
{% block body %}
<!--Display using the contents of content-->
<h1>{{content.title}}</h1>
<div>{{content.body}}</div>
<p>{{content.date}}</p>
<div>{{content.body}}</div>
{% endblock %}

Up to this point, the following page will be displayed at http://127.0.0.1:5000. スクリーンショット 2016-05-14 17.56.32.png

Click each link to see the contents of SQLite. For example, if you follow the python link, it looks like the following. スクリーンショット 2016-05-14 17.57.11.png

It is displayed using the contents of SQLite python. (I was able to get it) The contents of the following id = 2.

{confirm_sqllite2.}


(flaski)hoge:flaski hoge$ sqlite3 wiki.db 
SQLite version 3.8.5 2014-08-15 22:37:57
Enter ".help" for usage hints.
sqlite> select * from wikicontents;
1|Flask|micro framework|2016-05-14 15:04:24.246057
2|python|pppython|2016-05-14 15:04:24.246057
3|kobito|kakure-momojiri|2016-05-14 15:04:24.246057

Insert / Update (POST) into SQLite table with API post

Try inserting and updating the SQLite table.

file organization

├── flaski
│   ├── __init__.py
│   ├── database.py
│   └── models.py
└── app.py

{app.py}


# -*- coding: utf-8 -*-
from flask import Flask, render_template, abort, request
from flaski.models import WikiContent
from flaski.database import db_session
from datetime import datetime

app = Flask(__name__)
app.config['DEBUG'] = True


@app.teardown_request
def shutdown_session(exception=None):
    db_session.remove()


@app.route("/")
def hello():
    contents = WikiContent.query.all()
    return render_template("index.html", contents=contents)


@app.route("/<title>", methods=["GET"])
def show_content(title):
    content = WikiContent.query.filter_by(title=title).first()
    if content is None:
        abort(404)
    return render_template("show_content.html", content=content)

@app.route("/<title>", methods=["POST"])
def post_content(title=None):
    if title is None:
        abort(404)
    content = WikiContent.query.filter_by(title=title).first()
    #If the content cannot be obtained, insert it, so create an instance of WikiContent
    if content is None:
        content = WikiContent(title,
                              request.form["body"]
                              )
    #If the content can be obtained, it will be updated, so the content of the body and datetime=Set the current time
    else:
        content.body = request.form["body"]
        content.date = datetime.now()

    #Add the content of content and commit
    db_session.add(content)
    db_session.commit()
    return content.body

if __name__ == "__main__":
    app.run()

In this state, execute app.py.

To make an http request on the console, install httpie with pip install httpie.

{insert_sqlite.}


# body=Update with test from httpie
http --form POST http://localhost:5000/httpie body="test from httpie"

When I checked the contents, a record with id = 4 was added.

{confirm_sqllite3.}


sqlite> select * from wikicontents;
1|Flask|micro framework|2016-05-14 15:04:24.246057
2|python|pppython|2016-05-14 15:04:24.246057
3|kobito|kakure-momojiri|2016-05-14 15:04:24.246057
4|httpie|test from httpie|2016-05-14 19:32:12.075871

I will update it this time.

{update_sqlite.}


# body=Update with modified from httpie
http --form POST http://localhost:5000/httpie body="modified from httpie"

{confirm_sqllite4.}


sqlite> select * from wikicontents;
1|Flask|micro framework|2016-05-14 15:04:24.246057
2|python|pppython|2016-05-14 15:04:24.246057
3|kobito|kakure-momojiri|2016-05-14 15:04:24.246057
4|httpie|modified from httpie|2016-05-14 19:35:40.904904

It has been updated.

In this state, if you check http: // localhost: 5000, httpie is added.

スクリーンショット 2016-05-14 19.39.02.png

If you click httpie, you can see that it has been acquired in the updated state. I was able to POST.

スクリーンショット 2016-05-14 19.39.35.png

Recommended Posts

Create a simple web app with flask
Creating a simple app with flask
Create a web service with Docker + Flask
How to deploy a web app made with Flask to Heroku
Play like a web app with ipywidgets
Create a simple GUI app in Python
Create a GUI app with Python's Tkinter
Daemonize a Python web app with Supervisor
Easy web app with Python + Flask + Heroku
Web App Development Practice: Create a Shift Creation Page with Django! (Shift creation page)
Create an image composition app with Flask + Pillow
Make a simple pixel art generator with Flask
Vienna with Python + Flask web app on Jenkins
Start a simple Python web server with Docker
Create a bulletin board with Heroku, Flask, SQLAlchemy
Launch a web server with Python and Flask
How to create a multi-platform app with kivy
Create a web app that can be easily visualized with Plotly Dash
Web App Development Practice: Create a Shift Creation Page with Django! (Introduction)
Create a Todo app with Django REST Framework + Angular
Create a native GUI app with Py2app and Tkinter
Create a (simple) REST server
Easy machine learning with scikit-learn and flask ✕ Web app
Web application development with Flask
Create a Todo app with the Django REST framework
Create a Todo app with Django ③ Create a task list page
Create a heatmap with pyqtgraph
Create a web app that converts PDF to text using Flask and PyPDF2
Web application with Python + Flask ② ③
Create a simple textlint server
Create a directory with python
Create a Todo app with Django ⑤ Create a task editing function
Deploy a real-time web app with swampdragon x apache
Deploy a web app created with Streamlit to Heroku
Web application with Python + Flask ④
Web App Development Practice: Create a Shift Creation Page with Django! (Write a base template)
Web App Development Practice: Create a Shift Creation Page with Django! (Authentication system processing)
Web App Development Practice: Create a Shift Creation Page with Django! (Experiment on admin page)
Create a web application that recognizes numbers with a neural network
Create a machine learning app with ABEJA Platform + LINE Bot
I made a simple book application with python + Flask ~ Introduction ~
Create a simple video analysis tool with python wxpython + openCV
Create a simple Python development environment with VSCode & Docker Desktop
Tornado-Let's create a Web API that easily returns JSON with JSON
Create a web API that can deliver images with Django
Create a Todo app with Django ① Build an environment with Docker
(For beginners) Try creating a simple web API with Django
Create a simple CRUD app using Django's generic class view
Easy deep learning web app with NNC and Python + Flask
Create a CSV reader in Flask
Creating a Flask server with Docker
Run the app with Flask + Heroku
Create a virtual environment with Python!
Build a web application with Django
Creating a web application using Flask ①
Creating a web application using Flask ③
Create a poisson stepper with numpy.random
Creating a web application using Flask ④
Create a file uploader with Django
Web App Development Practice: Create a Shift Creation Page with Django! (Design of database model)
Steps to set up Pipenv, create a CRUD app with Flask, and containerize it with Docker