-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
run.py
74 lines (56 loc) · 1.87 KB
/
run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# Import Python packages
import json
import os
# Import Bottle
import bottle
from bottle import jinja2_template as template
from bottle import response, run, static_file
# Import Bottle Extensions
from bottle_sqlalchemy import SQLAlchemyPlugin
# Import SQLAlchemy
from sqlalchemy import Column, Integer, String, Text, create_engine
from sqlalchemy.ext.declarative import declarative_base
# Define dirs
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, 'static')
# App Config
bottle.TEMPLATE_PATH.insert(0, os.path.join(BASE_DIR, 'templates'))
bottle.debug(True) # Don't forget switch this to `False` on production!
# SQLite Database config
Base = declarative_base()
db_engine = create_engine('sqlite:///' + os.path.join(BASE_DIR, 'articles.db'))
# Starting App
app = bottle.default_app()
# Install Bottle plugins
app.install(SQLAlchemyPlugin(db_engine, keyword='sqlite_db'))
# Articles Database class
class ArticlesDB(Base):
__tablename__ = 'articles'
id = Column(Integer, primary_key=True)
title = Column(String(255), nullable=False)
description = Column(Text())
# API routes
@app.get('/api/articles/')
def get_all_articles(sqlite_db):
"""Get all Articles from Database"""
articles = []
articles_query = sqlite_db.query(ArticlesDB).all()
for i in articles_query:
articles.append({
'title': i.title,
'description': i.description
})
response.headers['Content-Type'] = 'application/json'
return json.dumps({'data': articles})
# Index page route
@app.get('/')
def show_index():
"""Show Index page"""
return template('index')
# Static files route
@app.get('/static/<filename:path>')
def get_static_files(filename):
"""Get Static files"""
return static_file(filename, root=STATIC_DIR)
# Run server
run(app, server='auto', host='localhost', port=8080, reloader=True)