http://www.kzfmix.com/flaski/
See here for how to install and use virtualenv.
$ mkvirtualenv flaski
$ workon flaski
(flaski):flask_test hoge$ pip install flask
(flaski):flask_test hoge$ pip install sqlalchemy
{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:
├── flaski
│ ├── __init__.py
│ ├── database.py
│ └── models.py
├── do_create.py
└── do_insert.py
{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.
http://omake.accense.com/static/doc-ja/sqlalchemy/session.html
Display the Web page using the table values created in SQLite earlier.
├── flaski
│ ├── __init__.py
│ ├── database.py
│ └── models.py
├── app.py
├── static
│ └── snake.jpg
└── templates
├── index.html
├── layout.html
└── show_content.html
{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
{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.
Click each link to see the contents of SQLite. For example, if you follow the python link, it looks like the following.
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
Try inserting and updating the SQLite table.
├── 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.
If you click httpie, you can see that it has been acquired in the updated state. I was able to POST.
Recommended Posts