Last active
September 21, 2015 03:31
-
-
Save berlotto/789c4060a2d9067262fb to your computer and use it in GitHub Desktop.
2nd version of restapi rest for the blog post.
This file contains hidden or 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
# -*- encoding: utf-8 -*- | |
# RESTFul api test for blog post | |
# Author: Sérgio Berlotto <[email protected]> | |
# Site: http://blog.programadorlivre.com | |
# restapi.py | |
import falcon | |
try: | |
import ujson as json | |
except Exception, e: | |
import json | |
import rethinkdb as r | |
from restapidb import DBNAME, TABLENAME, TOTAL_FRASES, HOST, PORT | |
import random | |
r.connect(HOST, PORT).repl() | |
class LeroleroResource: | |
def on_get(self, req, resp): | |
"""Retorna uma frase aleatória do banco de dados""" | |
regid = random.randint(0, TOTAL_FRASES-1) | |
minha_frase = r.db(DBNAME).table(TABLENAME).get(regid).run() | |
resp.body = json.dumps(minha_frase) | |
resp.set_header('Content-Type', 'application/json') | |
resp.content_type = "application/json" | |
def on_post(self, req, resp): | |
"""Salva o registro no banco de dados""" | |
req_body = req.stream.read() | |
novo_dado = json.loads(req_body) | |
retorno = r.db(DBNAME).table(TABLENAME).insert(novo_dado, return_changes=True).run() | |
novo_registro = retorno["changes"][0]['new_val'] | |
resp.body = json.dumps(novo_registro) | |
resp.set_header('Content-Type', 'application/json') | |
resp.content_type = "application/json" | |
api = falcon.API() | |
api.add_route('/frase', LeroleroResource()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment