Skip to content

Commit 63ca581

Browse files
authored
Merge pull request #1 from d0ivanov/master
Get upstream changes
2 parents 16a0ce8 + c89a8f7 commit 63ca581

10 files changed

Lines changed: 216 additions & 0 deletions

File tree

examples/flask/app.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import json
2+
import uuid
3+
4+
from flask import Flask
5+
from flask import request
6+
from flask import render_template
7+
8+
from model.post import Post
9+
from errors import register_error_handlers
10+
11+
12+
app = Flask(__name__)
13+
14+
register_error_handlers(app)
15+
16+
17+
@app.route("/api/posts", methods = ["POST"])
18+
def create_post():
19+
post_data = request.get_json(force=True, silent=True)
20+
if post_data == None:
21+
return "Bad request", 400
22+
post = Post(post_data["title"], post_data["content"])
23+
post.save()
24+
return json.dumps(post.to_dict()), 201
25+
26+
27+
@app.route("/api/posts", methods = ["GET"])
28+
def list_posts():
29+
result = {"result": []}
30+
for post in Post.all():
31+
result["result"].append(post.to_dict())
32+
return json.dumps(result)
33+
34+
35+
@app.route("/api/posts/<post_id>", methods = ["GET"])
36+
def get_post(post_id):
37+
return json.dumps(Post.find(post_id).to_dict())
38+
39+
40+
@app.route("/api/posts/<post_id>", methods = ["DELETE"])
41+
def delete_post(post_id):
42+
Post.delete(post_id)
43+
return ""
44+
45+
46+
@app.route("/api/posts/<post_id>", methods = ["PATCH"])
47+
def update_post(post_id):
48+
post_data = request.get_json(force=True, silent=True)
49+
if post_data == None:
50+
return "Bad request", 400
51+
52+
post = Post.find(post_id)
53+
if "title" in post_data:
54+
post.title = post_data["title"]
55+
if "content" in post_data:
56+
post.content = post_data["content"]
57+
return json.dumps(post.save().to_dict())
58+
59+
60+
@app.route("/", methods = ["GET"])
61+
def posts():
62+
return render_template("index.html")
63+
64+
65+
@app.route("/posts/<post_id>", methods = ["GET"])
66+
def view_post(post_id):
67+
return render_template("post.html", post=Post.find(post_id))
68+
69+

examples/flask/database.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import sqlite3 as sqlite
2+
3+
4+
DB_NAME = "example.db"
5+
6+
conn = sqlite.connect(DB_NAME)
7+
8+
conn.cursor().execute('''
9+
CREATE TABLE IF NOT EXISTS post
10+
(
11+
id INTEGER PRIMARY KEY AUTOINCREMENT,
12+
title TEXT,
13+
content TEXT
14+
)
15+
''')
16+
conn.commit()
17+
18+
19+
class SQLite(object):
20+
21+
def __enter__(self):
22+
self.conn = sqlite.connect(DB_NAME)
23+
return self.conn.cursor()
24+
25+
def __exit__(self, type, value, traceback):
26+
self.conn.commit()

examples/flask/errors.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import json
2+
3+
4+
class ApplicationError(Exception):
5+
6+
def __init__(self, message, status_code):
7+
Exception.__init__(self)
8+
self.message = message
9+
self.status_code = status_code
10+
11+
def to_dict(self):
12+
return { "message": self.message }
13+
14+
15+
def __handle_error(error):
16+
return json.dumps(error.to_dict()), error.status_code
17+
18+
19+
def register_error_handlers(app):
20+
app.register_error_handler(ApplicationError, __handle_error)

examples/flask/model/__init__.py

Whitespace-only changes.

examples/flask/model/post.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from database import SQLite
2+
from errors import NoValuePresentError
3+
4+
5+
class Post(object):
6+
7+
def __init__(self, title, content, post_id=None):
8+
self.id = post_id
9+
self.title = title
10+
self.content = content
11+
12+
def to_dict(self):
13+
return self.__dict__
14+
15+
def save(self):
16+
with SQLite() as db:
17+
cursor = db.execute(self.__get_save_query())
18+
self.id = cursor.lastrowid
19+
return self
20+
21+
@staticmethod
22+
def delete(post_id):
23+
result = None
24+
with SQLite() as db:
25+
result = db.execute("DELETE FROM post WHERE id = ?",
26+
(post_id,))
27+
if result.rowcount == 0:
28+
raise ApplicationError("No value present", 404)
29+
30+
@staticmethod
31+
def find(post_id):
32+
result = None
33+
with SQLite() as db:
34+
result = db.execute(
35+
"SELECT title, content, id FROM post WHERE id = ?",
36+
(post_id,))
37+
post = result.fetchone()
38+
if post is None:
39+
raise ApplicationError(
40+
"Post with id {} not found".format(post_id), 404)
41+
return Post(*post)
42+
43+
@staticmethod
44+
def all():
45+
with SQLite() as db:
46+
result = db.execute(
47+
"SELECT title, content, id FROM post").fetchall()
48+
return [Post(*row) for row in result]
49+
50+
def __get_save_query(self):
51+
query = "{} INTO post {} VALUES {}"
52+
if self.id == None:
53+
args = (self.title, self.content)
54+
query = query.format("INSERT", "(title, content)", args)
55+
else:
56+
args = (self.id, self.title, self.content)
57+
query = query.format("REPLACE", "(id, title, content)", args)
58+
return query
59+
60+
61+
62+
63+
64+

examples/flask/static/css/bootstrap.min.css

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/flask/static/js/bootstrap.min.js

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/flask/static/js/jquery-3.4.1.min.js

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<link href="{{ url_for('static', filename='css/main.css') }}" rel="stylesheet">
5+
</head>
6+
<body>
7+
<h1>Test page</h1>
8+
<script src="{{ url_for('static', filename='js/jquery-3.4.1.min.js') }}"></script>
9+
</body>
10+
</html>

examples/flask/templates/post.html

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
5+
</head>
6+
<body>
7+
<div>
8+
<h3> {{ post.title }} </h3>
9+
<p> {{ post.content }} </p>
10+
</div>
11+
<script src="{{ url_for('static', filename='js/jquery-3.4.1.min.js') }}"></script>
12+
</body>
13+
</html>

0 commit comments

Comments
 (0)