Last active
August 29, 2015 14:01
-
-
Save fernandojunior/45efd7f525338a82475c to your computer and use it in GitHub Desktop.
Aplicação Web Restful simples utilizando o microframework Flask e a extenção Flask-Classy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, g, request, jsonify, abort # http://flask.pocoo.org/ | |
from flask.ext.classy import FlaskView # http://pythonhosted.org/Flask-Classy/ | |
from db import DatabaseConnection, BaseManager, BaseEntity # https://gist.github.com/fernandojunior/63c6c676f6e16a1a7f0e | |
""" | |
Aplicação Web Restful simples utilizando o microframework Flask e a extenção Flask-Classy | |
Author Fernando Felix do Nascimento Junior | |
Gist https://gist.github.com/fernandojunior/45efd7f525338a82475c | |
""" | |
class Entry(BaseEntity): | |
def __init__(self, title, text, id=None): | |
self.id = id | |
self.title = title | |
self.text = text | |
@classmethod | |
def schema(cls): | |
return """ | |
drop table if exists entry; | |
create table entry ( | |
id integer primary key autoincrement, | |
title text not null, | |
text text not null | |
); | |
""" | |
class EntriesView(FlaskView): | |
""" | |
Classe que define views para gerenciar Entries. | |
Metodo HTTP - Metodo View - Acao - Exemplo | |
GET - index - Obtem informacoes sobre os recursos - http://<servername>/api/1.0/entries | |
GET - get - Obtem informacoes sobre um recurso - http://<servername>/api/1.0/entries/3 | |
POST - post - Cria um novo recurso - http://<servername>/api/1.0/entries (cria uma nova entry, a partir dos dados fornecidos com a requisicao) | |
PUT - put - Atualiza um recurso - http://<servername>/api/1.0/entries/123 (atualiza a entry #123, a partir dos dados fornecidos com a requisicao) | |
DELETE - delete - Deleta um recurso - http://<servername>/api/1.0/entries/123 (deleta entry #123) | |
Exemplo de requisicao AJAX: | |
$.ajax( | |
{ | |
url: '<servername>/api/1.0/entries/1', | |
type: "PUT", | |
contentType: "application/json; charset=utf-8", | |
data: JSON.stringify({ | |
title: "novo titulo da entry", | |
//text: "algum texto" | |
}), | |
dataType: "json", | |
success: function (data) { | |
alert("atualizando uma entry. Response: " + data.result); | |
} | |
} | |
) | |
""" | |
route_prefix = '/api/1.0/' | |
@property | |
def __objects(self): | |
return g.objects(Entry) | |
def index(self): | |
data = self.__objects.all() | |
result = [d.__dict__ for d in data] | |
return jsonify(entries=result) | |
def get(self, id): | |
if not self.__objects.has(id): | |
abort(404) | |
result = self.__objects.get(id).__dict__ | |
return jsonify(entry=result) | |
def post(self): | |
if not request.json: | |
abort(400) | |
if not 'title' in request.json: | |
abort(400) | |
if not 'text' in request.json: | |
abort(400) | |
e = Entry(request.json['title'], request.json['text']) | |
id = self.__objects.save(e) | |
self.__objects.commit() | |
return jsonify(result=id) | |
def put(self, id): | |
if not self.__objects.has(id): | |
abort(404) | |
e = self.__objects.get(id) | |
if 'title' in request.json: | |
e.title = request.json['title'] | |
if 'text' in request.json: | |
e.text = request.json['text'] | |
#for key, value in request.json: | |
# setattr(e, key, value) | |
self.__objects.update(e) | |
self.__objects.commit() | |
return jsonify(result='True'), 200 | |
def delete(self, id): | |
if not self.__objects.has(id): | |
abort(404) | |
self.__objects.delete(id) | |
self.__objects.commit() | |
return jsonify(result='True'), 200 | |
app = Flask(__name__) | |
EntriesView.register(app) | |
@app.teardown_appcontext | |
def close_db(error): | |
if g.db.connected: g.db.close() | |
@app.errorhandler(400) | |
def bad_request(error): | |
return make_response(jsonify( { 'error': 'Bad request' } ), 400) | |
@app.errorhandler(404) | |
def not_found(error): | |
return make_response(jsonify( { 'error': 'Not found' } ), 404) | |
def objects(entity): | |
alias = entity.__name__.lower() | |
if alias not in g.__objects: | |
g.__objects[alias] = entity.objects(g.db) | |
return g.__objects[alias] | |
def init(): | |
with app.app_context(): | |
g.db = DatabaseConnection('d22.db') | |
g.__objects = {} | |
g.objects = objects | |
app.run() | |
if __name__ == '__main__': | |
init() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment