Skip to content

Instantly share code, notes, and snippets.

@mrozo
Created April 29, 2016 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrozo/123b98bdcd37969183a9ce105087ac79 to your computer and use it in GitHub Desktop.
Save mrozo/123b98bdcd37969183a9ce105087ac79 to your computer and use it in GitHub Desktop.
Flask sqlalchemy + Flask jsontools example. This file shows how to join those two Flask extensions in order to create a restful api for accessing the database.
#
# author: mroz
# email: private@mrozo.pl
# page: github.com/mrozo
# license: BSD 2-Clause License
# Copyright (c) 2016, mroz
#
# Flask sqlalchemy + Flask jsontools example.
# This file shows how to join those two Flask extensions in order to create a restful api for accessing the database.
#
from flask import Flask, current_app
from flask.ext.jsontools import jsonapi, RestfulView
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from flask.ext.jsontools import JsonSerializableBase
from sqlalchemy import Column, Integer, Enum, Text, LargeBinary
from flask.ext.sqlalchemy import SQLAlchemy
import flask.ext.sqlalchemy
from flask_sqlalchemy import SQLAlchemy
from flask.ext.jsontools import DynamicJSONEncoder
class Config:
DATABASE_URI = "sqlite:///"
DEBUG=True
TEST=False
SQLALCHEMY_TRACK_MODIFICATIONS = True
db = SQLAlchemy()
#
# flask.ext.sqlalchemy shortcuts
#
Column = db.Column
Text = db.Text
Enum = db.Enum
LargeBinary = db.LargeBinary
Integer = db.Integer
class Server(JsonSerializableBase, db.Model):
__tablename__ = 'servers'
id = Column(Integer, primary_key=True, unique=True)
name = Column(Text(64), nullable=False)
description = Column(Text(256))
type = Column(Enum('MSV3'), nullable=False)
configuration = Column(LargeBinary)
url = Column(Text(512), nullable=False)
class Generic_Report(RestfulView):
decorators = (jsonapi, )
primary_key = ('id',)
def create(self):
with app.app_context():
current_app.db.session.add(
Server(
name="testowy ms",
description="opis testowego ms",
type="MSV3",
url="http://192l.168.1.100:90"
))
current_app.db.session.commit()
return {'message':'success'}
def get(self, id):
print('hi')
return id
def replace(self, id): return 're'
def update(self, id): return 'up'
def delete(self, id): return 'del'
def list(self):
return {
'list':[['a','b'],'c',[]],
'servers': Server.query.all(),
'sql': str(Server.query)
}
class App(Flask):
"""
Required config fields are:
DATABASE_URI - see sqlalchemy.create_engine() documentation for valid strings
DEBUG - boolean value
:var db: sqlalchemy.Session
"""
db = None
def init_database(self):
global db
self.db = db
self.db.init_app(self)
with self.app_context():
self.db.create_all(app=self)
self.db.session.add(Server(
name="testowy ms",
description="opis testowego ms",
type="MSV3",
url="http://192l.168.1.100:90"
))
self.db.session.commit()
def __init__(self, local_name, config_object=Config):
super(App, self).__init__(local_name)
self.json_encoder = DynamicJSONEncoder
self.config.from_object(config_object)
self.init_database()
self.init_routing()
def init_routing(self):
Generic_Report.route_as_view(self, "generic_report", ('/','/<int:id>'))
if __name__ == "__main__":
app = App(__name__)
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment